I'm getting "System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'" error while running the following code.
SqlConnection con = new SqlConnection(#"String_data");
public student_info()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string insert = "INSERT INTO Table VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(insert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted successfully");
con.Close();
}
Please change the line. As you are only providing SQL Command and not providing connection i.e., server name, database name, user id and password.
SqlCommand cmd = new SqlCommand(insert);
To
SqlCommand cmd = new SqlCommand(con, insert);
You can learn here in SqlCommand Class
Related
Here is my code, I'm not sure why I keep getting the error
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6MK4S6G;Initial Catalog=Domingo;Integrated Security=True");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[Job]
([JobCardNo], [CustomerNo], [JobTypeID], [Days])
VALUES ('" + TxtNo.ToString() + "', '" + Txtcust.ToString() + "', '" + TxtID.ToString() + "','" +Txtdays.ToString() + "')", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Write("Data created successfully");
con.Close();
}
Heres my table in SQL Server:
INSERT INTO [dbo].[Job] ([JobCardNo], [CustomerNo], [JobTypeID],[Days])
VALUES (<JobCardNo, int,>, <CustomerNo, int,>, <JobTypeID, int,>, <Days, int,>)
I keep getting this error
Conversion failed when converting the varchar value 'System.Web.UI.WebControls.TextBox' to data type int.'
when running the code.
I reproduced your problem. As the comments said, TextBox does not use the ToString method but the Text property.
I made the following changes to your code, you could refer to the following code.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"constr");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[Job]
([JobCardNo], [CustomerNo], [JobTypeID], [Days])
VALUES ('" + int.Parse(TxtNo.Text) + "', '" + int.Parse(Txtcust.Text) + "', '" + int.Parse(TxtID.Text) + "','" + int.Parse(Txtdays.Text) + "')", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Write("Data created successfully");
con.Close();
}
The result is shown in the picture:
I'm probably blind or sm.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szymek\Desktop\Komunikator\Komunikator\Baza.mdf;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
con.Open();
String query = " INSERT INTO Uzytkownicy (imie, nazwisko, e-mail,login, haslo) VALUES ('"+ textBox1.Text + "','" +textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show(" Zapisano ! ");
this.Hide();
Login move = new Login();
move.ShowDialog();
}
Error at query I think:
System.Data.SqlClient.SqlException: „Incorrect syntax near '-'.”
I wrote the query for inserting data to MySQL table "Persons":
SqlConnection con = new SqlConnection();
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
But it's not working. I have one connection for the whole database, but it's not working for a specific table. How I can create a connection between specific table to query in C#?
What is it? SqlConnection con = new SqlConnection() you need to pass a connection string which comprises DBname, username, pasword, server name ... etc; you are not passing those information anywhere then how can you expect it to connect to your database without having the information.
Pass the connection string either in constructor or using the property.
SqlConnection con = new SqlConnection(connection_string)
(OR)
SqlConnection con = new SqlConnection();
con.ConnectionString = connection_string;
There are different ways to insert data into the tables. I suggest to use parametrized sql query to keep safe from malicious occurrence.
Firstly you should have a ConnectionString something like this:
string connectionString = "Persist Security Info=False;User ID=UserName;Password=YourPassword;Server=ServerName";
And than:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TableName (Col1, Col2, ColN) VALUES (#Col1, #Col2, #ColN)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Col1", txtName.Text);
cmd.Parameters.AddWithValue("#Col2", txtPhone.Text);
cmd.Parameters.AddWithValue("#ColN", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Try this code. Please edit your credentials before trying.
Replace localhost with SQL server instance name, user id with your MySQL server instance user id, password with your MySQL server instance password and testdb with your database name. It should work fine.
string connectionString = #"server=localhost;user id=admin;password=admin;database=testdb;";
SqlConnection con = new SqlConnection(connectionString);
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
I have a Form that contains an "Add" button and a textBox, which is used to add information to a database table.
I need to check if the code entered in the TextBox is available before I can insert it.
My problem is that I get errors, as it attempts to add a "duplicate primary key" and I'm unsure of the source of error.
Below is the code I currently have:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
String reqt1="select numero_cpte from compte where numero_cpte="+textBox1.Text+";";
SqlCommand sql1 = new SqlCommand(reqt1, connection1);
int d = int.Parse(textBox1.Text);
int dd = Convert.ToInt32(sql1.ExecuteScalar());
if(d == dd)
{
int o1 = sql1.ExecuteNonQuery();
MessageBox.Show("this account is not valide!!","Fiche ");
connection1.Close();
}
if (String.IsNullOrEmpty(textBox1.Text) == true)
{
MessageBox.Show("You should insert the code!!","Fiche",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand sql = new
SqlCommand("insert into compte values(" + textBox1.Text + ",'" +
textBox2.Text + "','" + type_cpteComboBox.SelectedItem.ToString() +
"','" + textBox2.Text + "','" + comboBox1.SelectedItem.ToString() +
"'," + comboBox2.SelectedItem.ToString() + ",'" +
checkBox1.Checked.ToString() + "','" + checkBox2.Checked.ToString() +
"','" +textBox5.Text+ "','" +textBox6.Text+ "');", connection);
int o = sql.ExecuteNonQuery();
MessageBox.Show(o + "Success of add","Fiche");
connection.Close();
textBox1.Text = "";
textBox2.Text = "";
}
This is the error I see:
The insert command works perfectly, but When I try to test if the code that I'am going to add in the base exists or not (by typing a code that I know exists), I get this exception.
It looks like your code drops down into the add code even if you have discovered that your number is a duplicate. Try adding "return;" after you close the connection.
MessageBox.Show("Ce compte existe.Veuillez sasir un numéro de compte valide!!", "Fiche Comptes");
connection1.Close();
return;
private object ExecuteScalar(string sql)
{
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
SqlCommand sql1 = new SqlCommand(sql, connection1);
return sql1.ExecuteScalar();
}
}
The advantage of this is that you always know that your connection will be closed when you are done. Even if you are only going to be calling this method once, it improves readability and is therefore helpful.
I have tried so many types I don't know how to insert.
Is there any problem with sql server?
PLEASE HELP ME FAST..
SqlConnection con = new SqlConnection( "Data Source=localhost/SQLEXPRESS.Polaris.dbo;Initial Catalog=Polaris;Integrated Security=True;Pooling=False");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
SqlDataReader rdr = null;
//string s1 = "insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'";
SqlCommand cmd1 = new SqlCommand("insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'");
cmd1.Connection = con;
rdr = cmd1.ExecuteReader();
Label2.Visible = true;
//EndEventHandler.RemoveAll();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
Cannot implicitly convert type 'WebApplication4.SqlConnection' to
'System.Data.SqlClient.SqlConnection'
According to error you have class called SqlConnection in WebApplication4 namespace. You may have mistakenly generate that class. you need to remove that class first and then add reference to System.Data.SqlClient
Here's what you can do:
SqlConnection con = new SqlConnection( "Data Source=localhost/SQLEXPRESS.Polaris.dbo;Initial Catalog=Polaris;Integrated Security=True;Pooling=False");
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
string s1 = "insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'";
SqlCommand cmd = new SqlCommand(s1, con);
cmd.ExecuteNonQuery();
}