使用Command对象执行数据库操作

using System.Configuration;
using System.Data.SqlClient;
using System.Xml;
namespace test
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.Label Label3;
private string con=ConfigurationSettings.AppSettings
["DBConnString"].ToString();

private object ExecuteScalarMySqlCommand()
{
String cmdText="select Staff_name from Staff";
SqlConnection myConnection=new SqlConnection
(con);
SqlCommand myCommand=new SqlCommand
(cmdText,myConnection);
myConnection.Open();
object scalarobject=myCommand.ExecuteScalar();
myConnection.Close();
return(scalarobject);
}
private void ExecuteNonQueryMySqlCommand(String newName)
{
String cmdText="UPDATE Staff Set
staff_name=´ "+newName+"´ where staff_id=1";
//String cmdText="insert into Staff
(staff_name) values(´ "+newName+"´ )";
SqlConnection myConn= new SqlConnection(con);
SqlCommand myCMD = new SqlCommand
(cmdText,myConn);
myConn.Open();
myCMD.ExecuteNonQuery();
myConn.Close();
}
private String ExecuteXmlReaderMySqlCommand()
{
String cmdText="Select staff_name from staff
for xml auto";
SqlConnection MyConn=new SqlConnection(con);
SqlCommand myCMD=new SqlCommand
(cmdText,MyConn);
MyConn.Open();
XmlReader xmlReader=myCMD.ExecuteXmlReader();
String xmlString="";
while(xmlReader.Read())
{
xmlString+=xmlReader.ReadOuterXml()
+"\n";
}
xmlReader.Close();
MyConn.Close();
return(xmlString);
}
private void Page_Load(object sender, System.EventArgs
e)
{
//Response.Write(connectsrt);
if(!Page.IsPostBack)
{
Label1.Text=ExecuteScalarMySqlCommand
().ToString();

ExecuteNonQueryMySqlCommand("王凤凰");
Label2.Text=ExecuteScalarMySqlCommand
().ToString();

TextBox1.Text=ExecuteXmlReaderMySqlCommand();
}
}
}

原文地址:https://www.cnblogs.com/hhq80/p/611076.html