I am trying to insert to a SQL database in my C# application.
I've read a bit of documentation, and came up with what I thought would work. In reality, what happens is that when the user has entered thier data and presses the submit button, the app freezes for a moment, then gives me a "SqlException", and mentions something about not being able to connect.
I am not sure I used the connection string correctly so I am asking for help.
These are the methods I used to build the query and make the connection:
private void btn_Submit_Click(object sender, EventArgs e)
{
if (isValidData())
{
//MessageBox.Show("Valid", "All Entries Were Valid!");
//CONVERT FORM VALUES AND STORE IN VARIABLES TO SEND TO MYSQL QUERY
DateTime saleTime = saleDatePicker.Value;
Decimal price = Convert.ToDecimal(txt_Price.Text);
string customerName = txt_CustomerName.Text;
string customerPhone = txt_CustomerPhone.Text;
string description = rTxt_Description.Text;
//Build Query string
string query = "INSERT into SALES VALUES ('" + saleTime + "','" +
price + "','" + customerName + "','" + customerPhone + "','" +
description + "');";
insertValues(query);
}
}
private void insertValues(string q)
{
SqlConnection sqlConnection1 = new SqlConnection("Server=host;Database=dbname;User Id=username;Password=password;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = q;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
}