C# 窗体应用程序中怎样将数据写入数据库? 100
数据库为: 展开
新增引用
namespace Test1
{
public partial class Form2 : Form
{
SqlConnection sqlconn = null;
SqlCommand sqlcomm = null;
SqlDataAdapter sqlda = null;
DataSet ds = null;
string strconn = "";
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
sqlconn = new SqlConnection();
sqlcomm = new SqlCommand();
strconn = "data source=(local);database=room;user id=sa;password=sa;Integrated Security=SSPI";
sqlconn.ConnectionString = strconn;
sqlconn.Open();
if (sqlconn.State == ConnectionState.Open)
MessageBox.Show("连接成功");
sqlcomm.Connection = sqlconn;
sqlcomm.CommandType = CommandType.Text;
}
private void button_sure_Click(object sender, EventArgs e)
{
string strSQL3= "insert into table (room,style,value) values (label_F.Text,label_D.Text,label_D.Text)";//需要加的再加
SqlCmd.CommandText = strSQL3;
SqlCmd3.ExecuteNonQuery();
}
}
}
//数据库连接字符串
SqlConnection conn3 = new SqlConnection(str3);
//新建数据库连接对象
conn3.Open();
//实现连接,打开数据库
SqlCommand cmd = new SqlCommand("insert into 表 (列名,列名,列名) values('数据','数据','数据')", conn3);
//插入数据
cmd.ExecuteNonQuery();
//执行SQL语句
conn3.Close();
//关闭数据库
如 connection command dataadapter等。利用这三个类可以实现对数据库的各种操作
using (SqlConnection sqlCon = new SqlConnection(strCon))
{
string sqlQuery = @"insert table_name (id,name) values (1,'hello')";
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlCon);
sqlCmd.CommandType = CommandType.Text;
try
{
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
}
catch
{
//write error log
}
finally
{
sqlCmd.Dispose();
sqlCon.Close();
}
}
完全懂。你可以在代码后加详细注释吗?
在vs2010中,当你的鼠标放上去时就会显示解释,还有就是有.的地方你重新点下就知道了
建议你看点资料就行了