通过SqlCommand对象的ExecuteNonQuery方法执行命令行,来实现数据库中表的增、删、改。主要有5步
using System.Data.SqlClient;//载入数据库命名空间
private void button1_Click(object sender, EventArgs e)
{
//、连接数据库
SqlConnection con = new SqlConnection("Server=CAIWU;User Id=sa;Pwd=;DataBase=db_Me");
//命令行语句,在表中添加内容。'"+string格式内容+"',"+数字格式内容+"
string strInsert = "insert into dbo.Table_2(Name,Price) values('"+textBox1.Text+"',"+Convert.ToInt32(textBox2.Text)+")";
//2、加入命令行语句
SqlCommand com = new SqlCommand(strInsert, con);
if (con.State == ConnectionState.Closed)
{
con.Open();//3、打开数据库连接
}//4、SqlCommand对象的ExecuteNonQuery方法执行命令行,并返回受影响的行数
if (Convert.ToInt32(com.ExecuteNonQuery()) > )
{
label3.Text = "添加成功!";
}
else
{
label3.Text = "添加失败!";
}
con.Close();//5、关闭数据库连接
}
其他详情可参考:
https://blog.****.net/c1481118216/article/details/51766590?utm_source=blogkpcl12
https://www.cnblogs.com/daxueshan/p/6687521.html