Not sure how to initialise the database connection - c#

I am trying to insert into my SQL database table called Questions, whenever I click on the button the error below comes up and I'm not sure how to solve this problem as I thought I only needed to open the database connection then close it afterwards?
Any help would be very helpful.
private void button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)");
command1.ExecuteNonQuery();
connect.Close();
}
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteNonQuery: Connection property has not been initialized.

Error message is clear;
You did not connect your SqlCommand and SqlConnection. Use your connection as a second parameter in your command like;
SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)",
connect);
Or you can use CreateCommand when you create your SqlCommand based on your connection. Also use using statement to dispose your connection and command automaticly instead of calling .Close() method manually.
Best way possible;
private void button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
using(var connect = new SqlConnection(connectionString))
using(var command1 = connect.CreateCommand())
{
command1.CommandText = "INSERT INTO Questions ([Question Type]) VALUES (1)";
connect.Open();
command1.ExecuteNonQuery();
}
}

Related

Insert into database button code not working unsure how to fix it

I have tried to fix it but it wont take the three words i try to insert. it says error
"Format of the initialization string does not conform to specification
starting at index 0."
here is the button code
private void button5_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("ConnectionOne");
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport) values('" + this.food_txt.Text + "','" + this.hobby_txt.Text + "','" + sport_txt.Text + "');");
cmd.ExecuteNonQuery();
con.Close();
}
The ConnectionOne is the name of the connection i have made with the data base
I strongly suspect you have a variable as ConnectionOne and this saves your string.
In such a case, you need to use it as;
SqlConnection con = new SqlConnection(ConnectionOne);
But more important, you should always use paramterized queries. This kind of string concateanations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand instead of calling .Close() method manually.
private void button5_Click(object sender, RoutedEventArgs e)
{
using(var con = new SqlConnection(ConnectionOne))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport)
values(#food, #hobbies, #sport)";
cmd.Parameters.AddWithValue("#food", this.food_txt.Text);
cmd.Parameters.AddWithValue("#hobbies", this.hobby_txt.Text);
cmd.Parameters.AddWithValue("#sport", sport_txt.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}

exception thrown while connecting to database: connection property has not been initialized

I am trying basic database insert and this code is waht I am running in visual studio 2010:-
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
where am I wrong?
You created a connection and opened it, but you did not associate it with the SqlCommand. You can do this a couple of ways, either in the constructor of the SqlCommand or through the Connection property of the SqlCommand.
Additionally, you should use parameterized queries to prevent SQL Injection attacks. I'd also recommend putting the SqlConnection in a using block to ensure it is closed and properly disposed of. Putting all of that together gives you something like this:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("insert into names values(#name)", conn);
// Alternatively, you could do cmd.Connection = conn if you didn't pass
// the connection object into the SqlCommand constructor
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.ExecuteNonQuery();
}
}
You did not assign the connection to the command object. try:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
cmd.Connection = conn; // <- this is the missing line
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

insert in sql using c#

this code is successfully inserting a new value in a SQL db, but only when I insert constant values.
I need help where it says **(?)** in the code below, where I want to insert new values without specifying constants in the code.
What I mean is, I want to be able to type any random value in output window and it gets inserted into the SQL db.
private void InsertInfo()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
connetionString = #"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connetionString);
string sql = "insert into record (name,marks) **values( ?))";**
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
There is no need to use an adapter here; that is not helping you. Just:
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into record (name, marks) values (#name, #marks)";
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("marks", marks);
conn.Open();
cmd.ExecuteNonQuery();
}
or with a tool like "dapper":
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString)) {
conn.Open();
conn.Execute("insert into record (name, marks) values (#name, #marks)",
new {name, marks});
}
Those '?' are termed as parameters. From what I understand, you are wanting to use a parametrized query for your insert which is a good approach as they save you from chance of a SQL injection. The '?' sing in your query is used when you are using an
OLEDBConnection & Command object.
Normally, you would use '#' symbol to specify a parameter in your query. There is no need for an adapter. You just
//Bind parameters
// Open your Connection
// Execute your query
// Close connection
// return result
Parametrized queries 4 Guys from Rolla
MSDN: How to Protect from SQL injection in ASP.NET

Connecting C# to a remote MySQL database

I am trying to connect a C# application to my MySQL database located in a remote server. When I try to execute this simple program, I get the following error: sqlException was unhandled
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("user id=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
SqlCommand com = new SqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
The SqlClient namespace is for connecting to Microsoft SqlServer databases. If you want to work with MySql, you'll need to find an ADO.NET implementation (3rd party) or determine if there is a way to make it work with OleDb/Odbc.
UPDATE
Apparently, MySql provides its own ADO.NET driver for getting the job done.
As Brian pointed out, you are using the wrong provider. Also, your connection string is wrong. It should read
"Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
You can reference this site for all of the different connection string types for mysql
Here is what you need to download
Keep in mind that Classes for working with MySql in .NET are mostley the same as working with MSSQL with exception that they have My... prefix
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("userid=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
MySqlCommand com = new MySqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
first of all, you know what is forms of connect string and then established the connection with the database.
bb rec
private void btnretrive_Click(object sender, EventArgs e)
{
string cs = "server=localhost;user id=root;database=world;";
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from world;",conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dataGridView1.DataSource = table;
conn.Close();
}

Can't get output from SQL Server Compact

I have the following code behind a button in Visual Studio 2010
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection Con = new SqlCeConnection();
Con.ConnectionString = "Data Source = 'DB.sdf';" + "Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin");
try
{
Con.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCeDataReader Reader=Query.ExecuteReader();
MessageBox.Show(Reader["Password"].ToString());
}
It works fine execute and no exception in connection but when I press the button it raises an exception saying
Error: Execute Reader Connection Property Has Not Been Initialized
I'm not going to attempt to comment on database access code in a UI event handler, it will detract from the answer too much. All I will say is, try not to do it.
You haven't associated the connection with the command, either in the command constructor or the relevant Connection property.
I would re-write the entire method to the following to cut out the dangerous try-catch (catching everything, very bad practice) and to utilise the fact using statements also handle object disposal for you:
string password = null;
using (var conn = new SqlCeConnection("Data Source = 'AlviMBRental.sdf'; Password='my Password';"))
using (var comm = new SqlCeCommand("SELECT Password FROM Admin", conn))
{
conn.Open();
using (var reader = comm.ExecuteReader())
{
password = (string)reader["Password"];
} // Dispose reader
// Alternatively, if the resultset is single column and single row, you can do:
var passwordScalar = (string)comm.ExecuteScalar();
} // Dispose command, close / dispose connection.
MessageBox.Show(password ?? "No password found.");
You are not associating your command with your connection - try this:
SqlCeConnection Con = new SqlCeConnection("Data Source = 'AlviMBRental.sdf';Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin", Con); // <== specify "Con" here!
Otherwise, your SqlCeCommand has no connection to work with....
Try like this:
private void button1_Click(object sender, EventArgs e)
{
var connectionString = "Data Source='AlviMBRental.sdf';Password='my Password';";
using (var con = new SqlCeConnection(connectionString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT Password FROM Admin";
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show(reader["Password"].ToString())
}
}
}
}
Make sure you have associated the connection with the command object. Also make sure you have wrapped IDisposable objects in using statements as shown in my example.

Categories

Resources