2012-10-19 71 views
-2

当我写这个代码中插入一行到数据库:异常插入一行到数据库

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString); 
//string insCmd = "Insert into [node] (title, parent_id, oid, display, linkById, customLinks, contentType) values (@title, @parent_id, @oid, @display, @linkById, @customLinks, @contentType)"; 
string insCmd = "Insert into [node] (title) values (@title)"; 
SqlCommand insertUser = new SqlCommand(insCmd, con); 
insertUser.Parameters.AddWithValue("@title", TextBoxTitle.Text); 

try 
{ 
    insertUser.ExecuteNonQuery(); 
    con.Close(); 
    Response.Redirect("addNode.aspx"); 
    Label1.Text = "update success"; 

} 
catch (Exception er) 
{ 
    Label1.Text = er.StackTrace; 
} 

堆栈跟踪:

at System.Data.SqlClient.SqlConnection.GetOpenConnection(String method) 
at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) 
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) 
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) 
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 
at Admin_addNode.Button1_Click(Object sender, EventArgs e) 
in c:\inetpub\web1\Admin\addNode.aspx.cs:line 52 

任何人都知道出了什么问题?

+1

我们可以有例外类型和消息以及堆栈跟踪前第一? – Rawling

+2

_“任何人都知道问题出在哪里?” - 是的,你必须在你的catch子句中设置断点并查找异常。现在只打印相关的堆栈跟踪,但不显示实际的异常。设置一个断点,检查异常并在网上搜索它。如果您无法找到解决方案,请提出一个关于如何解决问题的问题,展示您尝试过的方法。 – CodeCaster

回答

4

呼叫con.Open()执行ExecuteNonQuery()

con.Open(); 
insertUser.ExecuteNonQuery(); 
+0

耶〜谢谢,我太累了 – hkguile

+0

不客气@hkinterview!顺便说一句,程序员也需要睡觉:D –

+0

@JohnWoo - 真的!不知道:) –