在asp.net中将gridview中的数据保存到本地数据库中
本文关键字:保存 数据库 数据 asp net 中将 gridview | 更新日期: 2023-09-27 18:07:09
我目前正在编写一段代码,其中用户应该插入一些关于员工的信息,并按一个按钮填充填充gridview和另一个按钮填充gridview中的信息保存到本地数据库中。在运行我到目前为止写的东西时,有一个一致的错误说"SqlExeption未被用户代码处理"。我一直在设法修理它,但没有成功。它抱怨conn.Open();
这是一段特定的代码:
protected void SaveButton_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(@"Data Source = C:'EmployeeWebProject'EmployeeWebProject'App_Data'EmployeeDatabase.sdf"))
{
using (SqlCommand comm = new SqlCommand("SELECT * FROM Employee"))
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
StrQuery = @"INSERT INTO Employee VALUES ("
+ GridView1.Rows[i].Cells[0].ToString() + ", "
+ GridView1.Rows[i].Cells[1].ToString() + ", "
+ GridView1.Rows[i].Cells[2].ToString() + ", "
+ GridView1.Rows[i].Cells[3].ToString() + ", "
+ GridView1.Rows[i].Cells[4].ToString() + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
finally
{
}
}
要避免SQL注入并使用正确的参数化查询,以及使用SQL Server CE连接和命令对象,请尝试以下代码:
protected void SaveButton_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
// define connection string and INSERT query WITH PARAMETERS
string connectionString = @"Data Source = C:'EmployeeWebProject'EmployeeWebProject'App_Data'EmployeeDatabase.sdf";
string insertQry = "INSERT INTO Employees(Col1, Col2, Col3, Col4, Col5) " +
"VALUES(@Col1, @Col2, @Col3, @Col4, @Col5);";
// define connection and command for SQL Server CE
using (SqlCeConnection conn = new SqlCeConnection(connectionString))
using (SqlCeCommand cmd = new SqlCeCommand(insertQry, conn))
{
// add parameters to your command - adapt those *as needed* - we don't know your table structure,
// nor what datatype (and possibly length) those parameters are !
cmd.Parameters.Add("@Col1", SqlDbType.Int);
cmd.Parameters.Add("@Col2", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@Col3", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@Col4", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@Col5", SqlDbType.VarChar, 100);
conn.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
// set parameter values
cmd.Parameters["@Col1"].Value = Convert.ToInt32(GridView1.Rows[i].Cells[0]);
cmd.Parameters["@Col2"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["@Col3"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["@Col4"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["@Col5"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.ExecuteNonQuery();
}
}
}
finally
{
}
}