Inserting into an MySQL db using 1 connection (C#.NET) - c#

i'm having an issue using C# inserting multiple rows into a MySQL database, have the following code;
//Upload to mysql
string connStr = "server=server;user=username;database=databasae;port=3306;password=password;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
foreach (Channel chan in results)
{
// Perform databse operations
try
{
//Create sql statment with parameters
string sql = "INSERT INTO channels(ID, Name) VALUES (#id,#name)";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#id", chan.ID);
cmd.Parameters.AddWithValue("#name", chan.Name);
cmd.ExecuteNonQuery();
updateStatus("Inserted");
}
catch (Exception ex)
{
updateStatus(ex.Message.ToString());
}
conn.Close();
I seem to be getting "connection must be valid and open". From what i can see i'm passing the connection string correctly and i'm using ExecuteNonQuery. And idea's?
thanks

conn.Close(); should be outside the foreach.
The following would work :
//Upload to mysql
string connStr = "server=server;user=username;database=databasae;port=3306;password=password;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
foreach (Channel chan in results)
{
// Perform databse operations
try
{
//Create sql statment with parameters
string sql = "INSERT INTO channels(ID, Name) VALUES (#id,#name)";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#id", chan.ID);
cmd.Parameters.AddWithValue("#name", chan.Name);
cmd.ExecuteNonQuery();
updateStatus("Inserted");
}
catch (Exception ex)
{
updateStatus(ex.Message.ToString());
}
}
conn.Close();

Looks like the connection is inside the foreach loop. It should be outside the foreach loop.
conn.Close(); should be outside the foreach loop.

How about using
using(MySqlConnection conn = new MySqlConnection(connStr))
{
//your stuff in here
}
This is transformed into a try final block .. so should take care of your connection woes.

add finally block to the try catch code and put conn.close() in it.like
finally
{
if(conn.ConnectionSTate=Connectionstate.open)
{
conn.close()
}
}

Related

Error with Connection property has not been initialized

Well, I work little bit with C # and I'm starting to work with Database with C # now, I've googled in several places and I am unable to identify where it is wrong, everywhere say I need to open a connection, but it is already open .
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
con.Open();
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Use using, takes care of the closing and disposal for you just in case you forget to do it explicitly. Put it inside the try, you have the connection open command outside the try so it wont catch any connection error. You probably want to look at parameterizing your command too.
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table] (name, time) VALUES (#name,#time)", conn))
{
cmd.Parameters.AddWithValue("#name", "test");
cmd.Parameters.AddWithValue("#time", 1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
you need to assign the command to the connection. eg:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
//----
SqlCommand command = new SqlCommand(
queryString, connection);
//----
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}

T-SQL insert method in a C# application

Alright I am new to T-SQL and I am trying to get my insert method to work. The error I get is unknown constructor at my insert method. I am not sure why I have the error, I am sure I sure I haven't referenced something correctly. Thank you before hand!
SqlConnection dbConn = null;
LabelData LadelList = new LabelData();
try
{
using (dbConn = new SqlConnection(Properties.Settings.Default["connectionname"].ToString()))
LabelData addNewVersion = new LabelData(#"INSERT INTO PackLabelVersion (VersionID, VersionNumber, FormatID) VALUES (#VersionID, #VersionNumber, #FormatID)", dbConn);
addNewVersion.Parameters.AddWithValue("#VersionID", VersionID);
addNewVersion.Parameters.AddWithValue("#VersionNumber", VersionNumber);
addNewVersion.Parameters.AddWithValue("#Quantity", FormatID);
dbConn.Open();
addNewVersion.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
You don't need LabelData, instead it should be SqlCommand.
SqlCommand addNewVersion = new SqlCommand (#"INSERT INTO PackLabelVersion (VersionID,VersionNumber,FormatID) VALUES (#VersionID,#VersionNumber,#FormatID)", dbConn);
also you need to define scope of using statement, currently it is just considering a single statement below it.
Your using statement does not have braces surrounding the database connection. Therefore it is disposed of right away.
SqlConnection dbConn = null;
LabelData LadelList = new LabelData();
try
{
using (dbConn = new SqlConnection(Properties.Settings.Default["connectionname"].ToString()))
{
SqlCommand addNewVersion = new SqlCommand(#"INSERT INTO PackLabelVersion (VersionID,VersionNumber,FormatID) VALUES (#VersionID,#VersionNumber,#FormatID)", dbConn);
addNewVersion.Parameters.AddWithValue("#VersionID", VersionID);
addNewVersion.Parameters.AddWithValue("#VersionNumber", VersionNumber);
addNewVersion.Parameters.AddWithValue("#Quantity", FormatID);
dbConn.Open();
addNewVersion.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
Edit.. Plus you need the SqlCommand not LabelData. (as per Habib)
You have syntax errors, missing SqlCommand, and the insert values are not set. (vicious cycle)
After declaring your sql connetion
SqlConnection cnn = new SqlConnection(" enter your connection string here ");
write this into the code block below.. it should work then
cnn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO PackLabelVersion (VersionID,VersionNumber,FormatID) VALUES (#VersionID,#VersionNumber,#FormatID)", cnn);
cmd.Parameters.AddWithValue("#VersionID", TextBox1.Text);
cmd.Parameters.AddWithValue("#VersionNumber", TextBox2.Text);
cmd.Parameters.AddWithValue("#FormatID", TextBox3.Text);
cmd.ExecuteNonQuery();
cnn.Close();

Cannot insert data into mbf database

I have been trying to insert data into a sql database for the last hours. for one or other reason I am able to connect to the database, but no data is inserted into the database. if I run the sql statement directly in the database it does seem to work. So therefore, I was able to conclude that the statement is correct. Furthermore, there were no errors in runtime. I have got the following c# code:
//Neither of these statements seem to work.
string sqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (#a,#b,#c,#d,#e,#f,#g,#h,#i)";
string altSqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (#a,#b,#c,#d,#e,#f,#g,#h,#i)";
foreach (DataRow row in importData.Rows)
{
using (SqlConnection conn = new SqlConnection(form1.Properties.Settings.Default.showConnectionString))
{
using (SqlCommand insertCommand = new SqlCommand())
{
insertCommand.Connection = conn;
insertCommand.CommandText = sqlStatement;
insertCommand.CommandType = CommandType.Text;
insertCommand.Parameters.AddWithValue("#a", row["CUE"].ToString());
insertCommand.Parameters.AddWithValue("#b", row["HH"].ToString());
insertCommand.Parameters.AddWithValue("#c", row["MM"].ToString());
insertCommand.Parameters.AddWithValue("#d", row["SS"].ToString());
insertCommand.Parameters.AddWithValue("#e", row["FF"].ToString());
insertCommand.Parameters.AddWithValue("#f", row["ADDR"].ToString());
insertCommand.Parameters.AddWithValue("#g", row["Event Description"].ToString());
insertCommand.Parameters.AddWithValue("#h", row["CAL"].ToString());
insertCommand.Parameters.AddWithValue("#i", row["PFT"].ToString());
try
{
conn.Open();
int _affected = insertCommand.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
}
}
}
}
if I change the connection parameters to something false, an error occurs, so that seems correct.
Any help would be greatly appreciated.
Thanks!
Alex
Try using this function as a template, big difference is that it is opening the connection before creating the command. I've not seen it done the way you have it setup. You also really should be opening the connection outside of the for loop, not in the for loop. Why open and close it repeatedly; the foreach should be inside the inner 'using'
public void ExecuteQuery(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
cmd.ExecuteNonQuery();
}
}
}

Retrieve number of columns in SQL Table - C#

I'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:
cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection
You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.
SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')
Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.
You have to use a command and retrieve back the scalar variable :
SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
use Executescalar() for getting a single element.
using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
{
con.Open();
try
{
using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
{
Int32 count = (Int32)getchild.ExecuteScalar();
}
}
}
Use ExecuteScalar
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
colnumber = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.
using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
SqlCommand cmd=new SqlCommand(Query,conn);
try
{
conn.Open();
}
catch (SqlException se)
{
throw new InvalidOperationException(String.Format(
"Connection error: {0} Num:{1} State:{2}",
se.Message,se.Number, se.State));
}
resultVar = (string)cmd.ExecuteScalar().ToString();
conn.Close();

Correct way to close database connection in event of exception

Does the following code leave the connection open if there is an exception?
I am using a Microsoft SQL compact edition database.
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
conn.Close();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
Surely a better way would be to declare a connection object before the try, establish a connection inside the try block and close it in a finally block?
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
finally
{
if( conn != null ) conn.Close();
}
The way you are handling SqlCeCommand in your code with the help of a using block, you could do the same for the SqlCeConnection.
SqlCeConnection conn;
using (conn = new SqlCeConnection(ConnectionString))
{
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
Note: You can use a using block for classes that implement IDisposable.
EDIT: This is same as
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "...";
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
ref: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28VS.80%29.aspx
Use Using
using(SqlConnection conn = new SqlConnection())
{
//put all your code here.
}
try
catch
finally
is the proper way to handle this, because connection should always be closed at the end. but you should check not only that conn != null, but also if conn state is not Closed.
You should use using statement, which handles the connection closing without hassles
http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx
You Have To Try Following Way.
Because Connection Close In Finally Block
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
}
finally
{
\\close connection here
}
Why not use a using around the connection as well as the SqlCeCommand ?

Categories

Resources