T-SQL insert method in a C# application - c#

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();

Related

How to actually execute a command?

I'm playing around making a POC and I've created the following call.
public string DoStuff()
{
try
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlConnection connection = new SqlConnection("Server...");
string command = "insert into Records values (...)";
adapter.InsertCommand = new SqlCommand(command, connection);
}
}
catch (Exception exception)
{
return exception.Message + " " + exception.InnerException;
}
return "WeeHee!";
}
The text I'm seeing returned is the happy one, so I conclude there's no exceptions. Hence, I conclude that the call to the DB is performed as supposed to. However, there's no new lines in the DB being created.
I'm using the same connection string as I have in my config file and the command in pasted in from SQL Manager, where it works.
So my suspicion was that although I create an insert command, I never actually execute it but according to MSDN that's how it's supposed to work.
What stupid thing do I miss here?
You are missing connection.Open(); and adapter.InsertCommand.ExecuteNonQuery();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlConnection connection = new SqlConnection("Server...");
connection.Open();
string command = "insert into Records values (...)";
adapter.InsertCommand = new SqlCommand(command, connection);
adapter.InsertCommand.ExecuteNonQuery();
}
You should use ExecuteNonQuery instead. Using an SqlDataAdapter for an INSERT query does not make sense.
Also you should Open your connection just before you execute it.
You can:
using(SqlConnection connection = new SqlConnection("Server..."))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "insert into Records values (...)";
connection.Open();
int craeted = command.ExecuteNonQuery();
}
The example you linked to returned a SQLAdapter for later use.
You don't need one at all:
using (SqlConnection connection = new SqlConnection("Server..."))
{
string command = "insert into Records values (...)";
connection.Open();
var command = new SqlCommand(command, connection);
command.ExecuteNonQuery();
}
Note that there are other execution methods, depending on expected return values and whether you want asynchronous operation: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

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();
}
}
}

C# Database adding to a table

I am using a .mdf database in Visual Studio 2010. When I add information to my table I get error. I don't get any problem when I add the first four rows. But when I add the fifth row I get error.
Here is the error:
SqlException was unhandled
What can the problem be?
dataAccess.AddQuestion("Category1", "Question1?", "1");
dataAccess.AddQuestion("Category2", "Question2?", "2");
dataAccess.AddQuestion("Category3", "Question3?", "3");
dataAccess.AddQuestion("Category4", "Question4?", "4");
dataAccess.AddQuestion("Category5", "Question5?", "5");
I get the error when I add the question number five.
Here is the method for how I add the information to the table in the database.
public void AddQuestion(string title, string question, string answer)
{
sqlConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(#Title, #Question, #Answer)", sqlConnection);
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("#Title", title));
sqlCommand.Parameters.Add(new SqlParameter("#Question", question));
sqlCommand.Parameters.Add(new SqlParameter("#Answer", answer));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
throw(ex);
}
}
Is there a reason not to use method scoped variables for the SQL objects? Try to use this:
public void AddQuestion(string title, string question, string answer)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(#Title, #Question, #Answer)", sqlConnection))
{
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("#Title", title));
sqlCommand.Parameters.Add(new SqlParameter("#Question", question));
sqlCommand.Parameters.Add(new SqlParameter("#Answer", answer));
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw;
}
}
}
If you consider moving to SQL Server 2008 or newer, you might also look into Table-Valued Parameters.
Why don't you use multiple insert statement to insert multiple rows at once as their is always a limit on the no of connection to database per app pool so either you must not close the connection or use multiple insert at once
try the following code maybe you need to lock()
private static readonly object Locker = new object();
public void AddQuestion(string title, string question, string answer)
{
lock (Locker)
{
try
{
sqlConnection = new SqlConnection("");
sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(#Title, #Question, #Answer)", sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("#Title", title));
sqlCommand.Parameters.Add(new SqlParameter("#Question", question));
sqlCommand.Parameters.Add(new SqlParameter("#Answer", answer));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("That is the Error:" ex.ToString()); // post this Text if it doesn't work
throw (ex);
}
}
}
I have found the problem (error)! In the database I was using nvarchar(50), but I hade one string which was 52 characters. I got the error because of that.

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

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()
}
}

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