2011-11-10 70 views
0

我试图吨的可能办法,但都无济于事,现在我已经“OledbException是未处理”试图捕获和抛出异常。请指教谢谢!C#OledbException被处理错误

(假设新的数据输入都是字符串不是整数。)

public partial class Form2 : Form 
{ 
    public Form2() 
    { 
     InitializeComponent(); 
    } 

    private void Form2_Load(object sender, EventArgs e) 
    { 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     //connect to database 
     string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb"; 
     OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString); 

     objConnection.Open(); 
     string newTagID = textBox1.Text; 
     string newUser = textBox2.Text; 
     string newAge = textBox3.Text; 
     string newPhoneNumber = textBox4.Text; 

     string InsertNewRecord = "INSERT INTO jiahe ([Tag ID], [User], [Age], [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')"; 
     OleDbCommand InsertCommand = new OleDbCommand(InsertNewRecord, objConnection); 

     try 
     { 
      InsertCommand.Parameters.Add("@[Tag ID]", newTagID); 
      InsertCommand.Parameters.Add("@[User]", newUser); 
      InsertCommand.Parameters.Add("@[Age]", newAge); 
      InsertCommand.Parameters.Add("@[Phone Number]", newPhoneNumber); 
      InsertCommand.ExecuteNonQuery(); 

      MessageBox.Show("Record Added!"); 
     } 

     catch (OleDbException ex) 
     { 
      throw ex; 
     } 

     finally 
     { 
      objConnection.Close(); 
     } 
    } 
} 

}

+0

什么行会抛出错误? – Mark

+0

catch(OleDbException ex) throw ex; } –

+0

如何当我尝试输入整数一切工作正常?我认为它应该是一个字符串,当我包装用户,年龄等与''? –

回答

1

你的问题是:为什么你得到 “OledbException是未处理”。

所以你的问题的答案(但不是你的问题)是你用throw抛出一个异常。取而代之的是,这样做:

MessageBox.Show(ex.ToString()); 

,会告诉你什么是你的代码背后的真正的错误,你将不得不处理的异常。

的oleDBException大概来,因为你应该使用下列定义SQL命令:

string InsertNewRecord = "INSERT INTO jiahe ([Tag ID], [User], [Age], [Phone Number]) VALUES (?newTagID, ?newUser, ?newAge,?newPhoneNumber)"; 

然后代码的其余部分将设置这些实际值替换@xxx的命令参数。 AddParameter会添加引号,所以你不需要。

+1

OleDb使用位置而不是命名参数。 “@__”的名字应该是“?”代替。而且,参数的一个关键特性是通过说其他代码将替换命令中的“@xxx”来表征它们是错误的。这_NEVER_发生。而是将单独的块传输到服务器以获取代码和数据。这是使参数安全的原因。 –

+0

感谢您指出这一点,将@s替换为?s。 – zmilojko

+0

乔尔你的意思是用@替换@?或?xxx? –