我试图通过填写文本框并单击保存来更新表中的列;我没有收到任何错误。没事!
这是我的存储过程:
ALTER PROCEDURE [dbo].[sp_UpdateProj]
@ORAID INT = NULL,
@FullTitle NVARCHAR(250) = NULL
AS
BEGIN
UPDATE tbl_ProjectFile
SET FullTitle = @FullTitle
WHERE ORAID = @ORAID
END
,当我在SQL Server Management Studio中运行它时,只要指定ID和标题名称,它就可以工作
这是我的C#代码
protected void Button_Save_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
con.Open();
string query = "sp_UpdateProj Where ORAID=" + int.Parse(TextBox_ORAID.Text);
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@ORAID", Convert.ToInt32(TextBox_ORAID.Text));
cmd.Parameters.AddWithValue("@FullTitle", TextBox_FullTitle.Text);
con.Close();
}
}
答案 0 :(得分:2)
您(几乎)正确地设置了所有内容-但您从未实际执行存储过程!
尝试以下代码:
protected void Button_Save_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
// the query string should be **ONLY** the stored procedure name - nothing else!
string query = "dbo.sp_UpdateProj";
// you should put **both** SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionStr))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.StoredProcedure;
// fill the parameters - avoiding "AddWithValue"
cmd.Parameters.Add("@ORAID", SqlDbType.Int).Value = Convert.ToInt32(TextBox_ORAID.Text);
cmd.Parameters.Add("@FullTitle", SqlDbType.NVarChar, 250).Value = TextBox_FullTitle.Text;
con.Open();
// you need to **EXECUTE** the command !
cmd.ExecuteNonQuery();
con.Close();
}
}
答案 1 :(得分:1)
Button_Save_Click
事件处理程序中存在一些错误:
当您使用commandType
为StoredProcedure
时,您只需传递存储过程名称
使用具有sp_
前缀的存储过程会导致性能问题(Using sp_ as prefix for user stored procedures in SQL server causing performance impact)
您忘记调用ExecuteNonQuery
方法
尝试以下代码:
protected void Button_Save_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
string procedureName = "dbo.UpdateProj";
using (SqlConnection con = new SqlConnection(connectionStr))
using(SqlCommand cmd = new SqlCommand(procedureName , con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ORAID", Convert.ToInt32(TextBox_ORAID.Text));
cmd.Parameters.AddWithValue("@FullTitle", TextBox_FullTitle.Text);
con.Open();
cmd.ExecuteNonQuery()
con.Close();
}
}
答案 2 :(得分:0)
您的查询行应为:
string query = "sp_UpdateProj";
您已经将参数作为其下方的对象。
然后添加
cmd.ExecuteNonQuery();
执行
答案 3 :(得分:0)
这是使用C#执行存储过程的简短信息