SqlConnection CON = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True");
private void button4_Click(object sender, EventArgs e)
{
try
{
CON.Open();
SqlDataAdapter SDA = new SqlDataAdapter("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + Gender + "','" + LANG_Hin + "')", CON);
SDA.SelectCommand.ExecuteNonQuery();
CON.Close();
MessageBox.Show("Saved SuccessFully!!!!!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
When I run this program I get:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll. Additional information: The connection
was not closed. The connection's current state is open.
Having a SQL connection object exist in a shared scope is a famously bad idea. The connection should be created, used, and disposed within the scope of the operation using it. Otherwise other code may try to use the same connection object (or even this same code more than once), leaving it in an unknown state. Which is very likely what's happening here.
Create the connection in the method itself:
private void button4_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection CON = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True"))
{
CON.Open();
SqlDataAdapter SDA = new SqlDataAdapter("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES(#Name,#Address,#Gender,#LangKnownHindi)", CON);
SDA.SelectCommand.Parameters.AddWithValue("#Name", textBox1.Text);
SDA.SelectCommand.Parameters.AddWithValue("#Address", textBox2.Text);
SDA.SelectCommand.Parameters.AddWithValue("#Gender", Gender);
SDA.SelectCommand.Parameters.AddWithValue("#LangKnownHindi", LANG_Hin);
SDA.SelectCommand.ExecuteNonQuery();
CON.Close();
}
MessageBox.Show("Saved SuccessFully!!!!!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Important: Also, note that I've done a couple of things here:
Wrapped the SqlConnection object in a using block. This basically creates a try/finally block which ensures that the connection is disposed after it's been used (by calling Dispose() in the finally block, so it only works on IDisposable objects). It's important to ensure disposal of I/O resources.
Replaced your SQL injection vulnerabilities with query parameters. You should always treat user input as parameter values, not as executable SQL code.
You should connect inside the method and handle disconnecting right. The easiest way to do so is by using using, which also disposes your connection handles in created in the background.
Also, in this case a SqlCommand fits the purpose better. Be aware of SQL injection too, since you concatenate user input to your SQL statement. Use parameters instead!
private void button4_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES(#name, #address,#gender,#lang)", conn))
{
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#address", textBox2.Text);
command.Parameters.AddWithValue("#gender", Gender);
command.Parameters.AddWithValue("#lang", LANG_Hin);
command.ExecuteNonQuery();
}
conn.Close();
MessageBox.Show("Saved SuccessFully!!!!!");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Are you sure dat u have used correct denoations of for 'myInfo' means caps nd small letters are in right order??..it is actually having an error in finding d database vid same name..use checkpoints in visual studio to check d execution of your program from starting..if you dont knw how to use checkpoints in visual studio den jst google d same..it vil show u step by step progress of ur code and den when u find error line of code just copy paste d line in sql server..if format of query in database and parameters given by you are correct den it vil execute in database or otherwise it vil fail to execute and vil show you error in sql statement
Related
I am working on Visual Studio 2013.
In the below code the MessageBox.Show("Connected to database") is shown correctly, but the SQL query is not inserting data into the database table.
When I insert data manually then it inserts without any problems. But unfortunately the data fails to insert on the button_click command.
private void DataAdd_Load(object sender, EventArgs e)
{
try
{
conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=Pathname;Integrated Security=True;Connect Timeout=30");
conn.Open();
MessageBox.Show("Connected to database");
cmd = new SqlCommand("INSERT INTO datains (name, dob, gender, occupation, height, weight, relation, polexpo) values('abc', '22-Aug-2001', 'Male', 'qwe2', '23', '431', 'qw23e', 'asqwed');", conn);
}
catch (Exception e1)
{
MessageBox.Show("Connection failed");
}
}
What have I done wrong here or anything I have missed?
You have forgotten to execute the query:
cmd.ExecuteNonQuery();
It is also better to close the connection after the work is done:
conn.Close();
You have to run the ExecuteNonQuery() method of your cmd to make it work, but it's also advisable to wrap both connection and command into a using statement so that they will be disposed (the connection should be also explicitly closed)
I found this article for the majority of the code here How to set SQL Server connection string?.
Here's what I have though:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(localdb)\\Instance;" +
"Initial Catalog=Database;" +
"User id=root;Password=pass;";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO Database.dbo.Table" +
"VALUES ('stg', 'stg1', 'stg2', 'stg3');", conn);
try
{
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
A lot of the previous code was giving me errors. At one point, I was getting an error that I couldn't connect to the instance. This was an issue with the '\'. It was recognizing it as an escape character, so I did double '\' to get rid of that, so I'm not getting that error anymore, so that shouldn't be the problem.
I was getting an error about the wrong username and password. I'm using SQL Server Authentication and the code I was previously using was specifying Windows authentication. I'm not getting that error anymore.
As of right now, the code executes all the way through with no errors. When I check on the database though (I'm using SQL Server Management Studio), nothing gets inserted into the table. I have ran the Insert statement directly and it works fine, so I'm not sure what the issue is here. Also, I'm using VS 2013.
You are not using SqlCommand.ExecuteNonQuery to use the insert-command at all. Therefore nothing is inserted.
SqlCommand myCommand = new SqlCommand("INSERT INTO Database.dbo.Table" +
"VALUES ('stg', 'stg1', 'stg2', 'stg3');", conn);
int inserted = myCommand.ExecuteNonQuery();
You should also use the using-statement to ensure that all unmanaged resources are disposed and the connection gets closed even on error. Then you don't need to use conn.Close explicitly.
You are not executing the query. Add this after creating the command object:
myCommand.ExecuteNonQuery();
Side note: You should rather have a try...catch around all the code, and use using blocks for the connection and command. That will ensure that the objects are closed and disposed properly whatever happens:
try {
using (SqlConnection conn = new SqlConnection()) {
conn.ConnectionString =
"Data Source=(localdb)\\Instance;" +
"Initial Catalog=Database;" +
"User id=root;" +
"Password=pass;";
conn.Open();
using (SqlCommand myCommand = new SqlCommand("INSERT INTO Database.dbo.Table" +
"VALUES ('stg', 'stg1', 'stg2', 'stg3');", conn)) {
myCommand.ExecuteNonQuery();
}
}
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
I'm receiving the following error message:
invalidOperationException was unhandled
In the following code:
private void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=DASTGIRKHAN\\SQLEXPRESS;Initial Catalog=DBProject;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + tfCode.Text + ",'" + tfName.Text + "','" + tfCell.Text + "','" + tfAdrs + "',)");
cmd.BeginExecuteNonQuery();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Inserted Successfully");
}
InvalidOperationException exception is thrown when you invoke BeginExecuteNonQuery method (msdn) and you not specified "Asynchronous Processing=true" in the connection string.
You should also set connection to your command:
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + tfCode.Text + ",'" + tfName.Text + "','" + tfCell.Text + "','" + tfAdrs + "')", conn);
InvalidOperationException
The name/value pair "Asynchronous Processing=true" was not included
within the connection string defining the connection for this
SqlCommand. The SqlConnection closed or dropped during a streaming
operation.
Sorry but your code has many errors. Let me show a different approach
private void btnInsert_Click(object sender, EventArgs e)
{
string cnString = #"Data Source=DASTGIRKHAN\\SQLEXPRESS;
Initial Catalog=DBProject;
Integrated Security=True;";
string cmdText = #"Insert INTO EmployeeRecord
Values(#code,#fname,#cell,#adr)";
using(SqlConnection conn = new SqlConnection(cnString))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#code", Convert.ToInt32(tfCode.Text));
cmd.Parameters.AddWithValue("#fname", tfName.Text );
cmd.Parameters.AddWithValue("#cell", tfCell.Text );
cmd.Parameters.AddWithValue("#adr", tfAdrs.Text);
int rowsInserted = cmd.ExecuteNonQuery();
if(rowInserted > 0)
MessageBox.Show("Inserted Successfully");
else
MessageBox.Show("Insert failes");
}
}
The primary cause of your error is stated by the answer of kmatyaszek, but this is just the tip of the iceberg.
You should always use the using statement around your disposable objects like the connection. This will ensure that the connection is closed and disposed also in case of exceptions.
You should use a parameterized query to create your command to avoid Sql Injection and parsing problems. For example, a single quote in the tfName textbox could lead to a Syntax Error.
The call to BeginExecuteNonQuery, excludes the call to ExecuteNonQuery and requires a call to EndExecuteNonQuery.
Finally, the result of ExecuteNonQuery tells you if the insertion is successful.
As a last note, I have remove the Pooling=False from the connection string.
You haven't said anything why do you want avoid his very useful optimization.
I'd print that SQL text. Looks like there's an unbalanced apostrophe to me.
Better yet, use a .NET class that binds parameters for you. Easier and better SQL injection projection, too.
What are tfCode, tfName,tfCell,tfAdrs? I assume they are textbox control?
if so you are using tfAdrs instead of tfAdrs.Text
also assign connection string to the command and remove additional space in
"Integrated security"
Why complicate yourself, use Parameterized Insert instead of concatenation, which its prone to SQL Injection.
SqlCommand command1 = new SqlCommand("INSERT INTO EmployeeRecord VALUES(#tfCode, #tfName, #tfCell, #tfAdrs)", conn);
command1.Parameters.AddWithValue("#tfCode", trCode);
command1.Parameters.AddWithValue("#tfName", tfName);
command1.Parameters.AddWithValue("#tfCell", tfCell);
command1.Parameters.AddWithValue("#tfAdrs", tfAdrs);
What I need to do is basically take the users name (which is already stored as a variable) and their score (which is also a variable) and store it in my database when they press 'submit'. Here is the code I have for the button click.
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
MySqlConnection myConn = new MySqlConnection(connStr);
}
Obviously i have changed the login details etc. I have had a look around and have only managed to find confusing codes about how to display data from a database in a form (i will do this later), but for now, i need to know how to add sName and iTotalScore into the database. (Fields are called 'Name' and 'Score' in DB)
You are going to use a combination of SqlConnection, SqlCommand and their properties. the connection is essentially the stuff of your code. The command is a literal SQL statement, or a call to a stored procedure.
A common C# idiom is to form your code around the very first line as shown here:
using (SqlConnection myConnection = new SqlConnection()) {
string doThis = "select this, that from someTable where this is not null";
SqlCommand myCommand = new SqlCommand(dothis, myConnection);
try {
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(); //pretend "myReader" was declared earlier
} catch (Exception myEx) {
// left to your imagination, and googling.
}
finally {
myCommand.Connection.Close();
}
}
// do something with the results. Your's to google and figure out
The general outline is
Using a connection
instantiate and configure an SqlCommand
Use try/catch as shown.
The "using" block gives use behind the scenes cleanup/disposal of all those objects we don't need anymore when we're done; in particular the SqlConnection object.
You must learn more about these Sqlxxxxx classes, there's lots of ways to configure them to do what you want.
I am not familiar with the MySql connector, but the code should be something along the lines of:
private void Insert()
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
string query = "INSERT INTO TableName('Name','Score) VALUES (#name, #score);";
using(MySqlConnection connection = new MySqlConnection(connStr))
{
MySqlCommand insertCommand = new MySqlCommand(connection,command);
insertCommand.Paramaters.AddWithValue("#name",sName);
insertCommand.Paramaters.AddWithValue("#score",iTotalScore);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
I created a connection with a Microsoft sql database and am trying to add basic informastion as part of an exercise but get the following error.
Object reference not set to an instance of an object
This is how I connect to the database
SqlConnection sqlConn;
protected void butConnect_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=lrmg;Integrated Security=True;";
sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
labMessage.Text = "a connection to your database was established";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
Here is where I get the error
protected void butSubmit_Click(object sender, EventArgs e)
{
try
{
string name = txtName.Text;
string date = txtDate.Text;
**SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES('" + name + "'," + date + ")";
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
}
I am under the impression that the sql connection was opened so why the exception?
You are getting the error because reference variable sqlConn is null - that is happening probably because
From you code snippet, connection is getting created and opened in
connect button click. So you need to hit connect before submit
Most likely cause is probably different assuming that this ASP.NET code - in such case, every request is served by different instance of page class - so if you open connection on one request (connect click), it (that variable) won't be available in next request (submit click). The remedy is simple - create and open connection when you need it i.e. in submit click. On the other hand, you probably need to understand mode about web programming models to avoid such mistakes.
You use two different events to do your work on the database. Why? Have you ever heard of connection pooling?
Probably between the first event (open connection) and second event (db insert) something happens and change your global variable SqlConn to null and you get the error. (Of course I am assuming that you press that button to open the connection before trying to insert anything)
With connection pooling this kind of programming pattern is no more necessary, instead, when you need to update/insert/delete/select something you open the connection, do your work and close immediately the connection without keeping it open and consuming resources on the server and client side.
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;" +
"Initial Catalog=lrmg;Integrated Security=True;";
using(SqlConnection sqlConn = new SqlConnection(connstring))
{
SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES(#name, #dt)";
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#dt", Convert.ToDateTime(txtDate.Text));
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
Notice also that your code is subject to Sql Injection attacks because you use string concatenation to build your sql text. This is a bad practice that should be avoided at all costs
You should have a dedicated method to open the connection, that you'd invoke every time you're using the connection. With your current setup, butConnect_click MUST be called before butSumbit_Click in the same request. So add the call to butConnect in butSubmit.