如何将数据添加到SQL Server Express数据库?
我写了以下代码
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLExpress;"
+"User Instance=true;" + "Integrated Security=true;"
+ "AttachDbFilename=|DataDirectory|GCdatabase.mdf;";
conn.Open();
//...
conn.Close();
这是对的吗?
如果是,那么如何将数据添加到表中?
答案 0 :(得分:3)
string connstring = @"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|GCdatabase.mdf;";
string insertSql = "INSERT INTO Table " +
"(Column1, Column2) VALUES " +
"(@Column2, @Column2); SELECT @@identity;";
using (SqlConnection connection =
new SqlConnection(connstring))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = insertSql;
command.Parameters.Add(new SqlParameter("@Column1", Column1));
command.Parameters.Add(new SqlParameter("@Column2", Column2));
connection.Open();
command.ExecuteNonQuery();
}
答案 1 :(得分:1)
有几种方法可以做到这一点。其中一个是使用带有SqlCommand
SQL语句的insert
对象:
SqlConnection conn = new SqlConnection();
conn.ConnectionString(/* your connection string goes here */);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into table values (1, 2, 3)", conn);
cmd.ExecuteNonQuery();
conn.Close();