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());
}
Related
I got this error during insert of data into a SQL Server database
Here is my code in button click event
try
{
string ConnString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf;Integrated Security=True;Connect Timeout=900,providerName=System.Data.SqlClient";
SqlConnection con = new SqlConnection(#ConnString);
SqlCommand cmd = new SqlCommand("InsertBodyTypeMaster", con);
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("bodytypename", txtBTname.Text.ToString());
con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
lblmessage.Text = "Record Inserted Succesfully into the Database";
lblmessage.ForeColor = System.Drawing.Color.CornflowerBlue;
}
con.Close();
con.Dispose();
}
catch (Exception ex)
{
lblmessage.Text = ex.ToString();
}
I see a few things wrong;
As mentioned, you need to change your Connect Timeout=900, to Connect Timeout=900;
You need to delete providerName=System.Data.SqlClient part since you already using the .NET provider for SQL Server. Provider names for .NET are implicit based on the implementing class and not needed to specified in the connection string. When you delete this, you will not need ; at the end of Connect Timeout=900; anymore
Use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Final connection string should be as;
string ConnString = "Data Source=(LocalDB)\v11.0,AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf;Integrated Security=True;Connect Timeout=900";
You have a comma and not a semi-colon after the 900 in the connect timeout property in the connection string.
Cause your connection string is total weird. remove those ; and replace them with ,. Also, make sure you spell them properly. It should be like
string ConnString = "Data Source=(LocalDB)\v11.0,AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf,Integrated Security=True,Connect Timeout=900;providerName=System.Data.SqlClient";
Also the below line
SqlConnection con = new SqlConnection(#ConnString);
It should be
SqlConnection con = new SqlConnection(ConnString);
You are calling Dispose() inside try block which is big blunder as shown below. Either use Using(...) block (or) finally block
try
{
....
con.Close();
con.Dispose();
}
Should be
finally
{
con.Close();
con.Dispose();
}
Looks like it's time you should start reading through documentation.
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
I develop a programe use c# Framework2.0 and Database is mysql.
I use transaction but always has error
System.InvalidOperationException: Connection must be valid and open to rollback transaction
at MySql.Data.MySqlClient.MySqlTransaction.Rollback()
Here is some of source code:
try
{
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
connection.Open();
MySqlCommand command = connection.CreateCommand();
MySqlTransaction myTrans = connection.BeginTransaction();
command.Connection = connection;
command.Transaction = myTrans;
try
{
string sql ="XXXXX";
command.CommandText =sql;
command.ExecuteNonQuery();
sql="yyyy";
command.CommandText =sql;
command.ExecuteNonQuery();
.........
myTrans.Commit();
}
catch (Exception ex)
{
myTrans.Rollback();
throw ex;
}
}
}
catch (Exception ex)
{
FileHelper.WriteLog(ex);
}
I check the sample from:
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqltransaction.html
The source code should be ok.
The error said the connection seems close already.
I think use Using() should be ok. it will close automatically.
Can Some help me with this?
Finally I find the solution .
The MySqlCommand.CommandTimeout default is 30 seconds.
maybe the server is old and data is big.
so timeout
so show error
Connection must be valid and open to rollback transaction
Just Set MySqlCommand.CommandTimeout=1200
this one can work fine.
it's really hard to find the root cause.
i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?
Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article
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.