SqlCommand()方法
SqlCommand cmd = new SqlCommand("insert into mynews value
('插入一条新数据')",
con);
Command对象的构造函数的参数有两个,一个是需要执行的SQL语句,另一个是数据库连接对象。创建Command对象后,就可以执行SQL命令,执行后完成并关闭数据连接,示例代码如下所示。
cmd.ExecuteNonQuery(); //执行SQL命令
con.Close(); //关闭连接
public partial class updatePage :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
string strKey =
Request.QueryString["key"];
string[] arr = strKey.Split(',');
string name =arr[0];
double lat =
Convert.ToDouble(arr[1]);
double lng =
Convert.ToDouble(arr[2]);
//SqlConnection sqlConn = new
SqlConnection("server=.;database=bike2;uid=sa;pwd=xue");
SqlConnection sqlConn = new
SqlConnection("server=localhost\\GISQZC;database=S-Location;integrated
security=SSPI");
sqlConn.Open();
StringBuilder sbSelect = new
StringBuilder("update TabBikeInfo1 set ");
sbSelect.Append("
longitude=@longitude,");
sbSelect.Append("
latitude=@latitude");
sbSelect.Append(" where
name=@name");//sbSelect-SQL语句:update TabBikeInfo1 set
longitude=@longitude,latitude=@latitude where name=@name
SqlCommand sqlCommand = new
SqlCommand(sbSelect.ToString(), sqlConn);//数据库命名对象
SqlParameterCollection sqlParameterCollection =
sqlCommand.Parameters;//为存储过程定义参数
sqlParameterCollection.Add("@name",
SqlDbType.NVarChar).Value = name;
sqlParameterCollection.Add("@longitude",
SqlDbType.NVarChar).Value = lng;
sqlParameterCollection.Add("@latitude",
SqlDbType.NVarChar).Value = lat;
int tt =
sqlCommand.ExecuteNonQuery();//执行SQL命令
if (tt > 0)
{
Response.Write("
success
");
}
else
{
Response.Write("
fail
");
}
}
}