I am trying to access and insert data with c# using ado.net. I have the sql server installed in my computer and hence I feel the machine name will be the server name. Following are the steps I am using to connect to the database.
private void dbButton_Click(object sender, EventArgs e)
{
connectionString = "Server = ITSL-SALT-33; Database = sampleADO; User Id = sa; Password = abcd;";
try
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
MessageBox.Show("Successfully connected to the database.");
insertButton.Enabled = true;
loadButton.Enabled = true;
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
MessageBox.Show("Connection attempt failed");
}
}
Below is the code for insert Button:
private void insButton_Click(object sender, EventArgs e)
{
cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @va2, @val3)";
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText= cmdString;
comm.Parameters.AddWithValue("@val1", txtBook.Text);
comm.Parameters.AddWithValue("@val2", txtAuthor.Text);
comm.Parameters.AddWithValue("@val3", txtPrice.Text);
comm.Parameters.AddWithValue("@val3", txtComments.Text);
try
{
MessageBox.Show(conn.DataSource);
Console.WriteLine(comm.ExecuteNonQuery());
Console.ReadLine();
}
catch(Exception exc)
{
MessageBox.Show("In Insert catch");
}
}
When I am trying to insert data, it is always showing in the messagebox that "in insert catch". I cannot understand where is the fault or if there is any step I am missing. I am new in using database or sql stuffs, just trying to learn how to interact with a database in .net. Please guide.
I think there is a just a small mistake just change you @va2
in your INSERT
query to @val2
and it should work now..
cmdString="INSERT INTO books (name,author,price) VALUES (@val1,
@va2 , @val3)";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.