Reputation: 47
I tried tons of possible ways but to no avail, and now i have "OledbException was unhandled" while trying to catch and throw exception. Please advise thanks!
(Assume new data inputs are all strings not integer.)
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();
}
}
}
}
Upvotes: 0
Views: 1610
Reputation: 2135
Your question is: why are you getting "OledbException was unhandled".
So the answer to your question (but not to your problem) is that you are re-throwing an exception with throw. Instead of that, do something like:
MessageBox.Show(ex.ToString());
That will show you what is the real error behind your code, and you will have handled the exception.
The oleDBException is probably coming because you should use the following to define the SQL command:
string InsertNewRecord = "INSERT INTO jiahe ([Tag ID], [User], [Age], [Phone Number]) VALUES (?newTagID, ?newUser, ?newAge,?newPhoneNumber)";
And then the rest of code will set those parameters replacing the @xxx in the command with actual values. The AddParameter will add quotes, so you do not have to.
Upvotes: 1