1.建立webservices
[WebMethod]
public DataSet ExecuteSQL(string sql)
{
DataSet ds = new DataSet();
if (sqlconn == null)
InitConn();
if (sqlconn != null)
{
try
{
SqlDataAdapter sda = new SqlDataAdapter(sql, sqlconn);
sda.Fill(ds);
}
catch (SqlException e)
{
Console.WriteLine("SqlException"+e.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception" + e.ToString());
}
}
return ds;
}
InitConn()函数:public DataSet ExecuteSQL(string sql)
{
DataSet ds = new DataSet();
if (sqlconn == null)
InitConn();
if (sqlconn != null)
{
try
{
SqlDataAdapter sda = new SqlDataAdapter(sql, sqlconn);
sda.Fill(ds);
}
catch (SqlException e)
{
Console.WriteLine("SqlException"+e.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception" + e.ToString());
}
}
return ds;
}
SqlConnection sqlconn = null;
private void InitConn()
{
try
{
if (sqlconn == null)
sqlconn = new SqlConnection("Data Source=<servername>;Initial Catalog=<dbname>;User ID=sa;Password=<pwd>;User Instance=False");
}
catch (Exception e)
{
System.Console.WriteLine(e.ToString());
System.Console.WriteLine(e.StackTrace);
}
}
调用的方式如下:private void InitConn()
{
try
{
if (sqlconn == null)
sqlconn = new SqlConnection("Data Source=<servername>;Initial Catalog=<dbname>;User ID=sa;Password=<pwd>;User Instance=False");
}
catch (Exception e)
{
System.Console.WriteLine(e.ToString());
System.Console.WriteLine(e.StackTrace);
}
}
private void button2_Click(object sender, EventArgs e)
{
Service s = new Service();
s.Url = "http://localhost/MyWebServices/Service.asmx";
try
{
DataSet ds = s.ExecuteSQL(this.textBox1.Text);
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
{
Service s = new Service();
s.Url = "http://localhost/MyWebServices/Service.asmx";
try
{
DataSet ds = s.ExecuteSQL(this.textBox1.Text);
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}