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.
Related
I have an SQL helper Class for my application, everything works nice as it should be, but in some code, I need to get the inserted ID using ##identity, what is the best way to do this ??
Here is My method in my SQL helper class :
public static void InsertUpdate_Data(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (SqlConnection connStr = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
}
}
}
And this is how I use it :
DBConn.InsertUpdate_Data("customer_add", CommandType.StoredProcedure,
new SqlParameter[]
{
new SqlParameter("#name", txt_name.Text.Trim()),
new SqlParameter("#gender", Gender_comb.Text),
new SqlParameter("#b_o_date", DOBTimePicker1.Value ),
new SqlParameter("#phone", Phone_txt.Text.Trim()),
new SqlParameter("#address", string.IsNullOrEmpty(Location_txt.Text) ? (object)DBNull.Value : Location_txt.Text.Trim()),
new SqlParameter("#note", string.IsNullOrEmpty(Note_txt.Text) ? (object)DBNull.Value : Note_txt.Text.Trim())
}
And also what is the best way to use SQL transactions in some code.
Thank you.
Don't use ##IDENTITY, it's unreliable.
The stored procedure should have, on the line immediately following the insert, SELECT SCOPE_IDENTITY(). Then you can use cmd.ExecuteScalar as mentioned.
For transactions, you have two options.
Either use conn.BeginTransaction() and don't forget to open the connection first, add transaction to command.Transaction, and put the transaction in a using block:
public static int InsertUpdate_Data(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open()
using (var tran = conn.BeginTransaction())
using (SqlCommand cmd = new SqlCommand(sql, connStr, tran))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
var result = (int)cmd.ExecuteScalar();
tran.Commit();
return result;
}
}
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
throw;
}
}
The other, possibly better, option is to use BEGIN TRANSACTION; and COMMIT TRANSACTION; in the procedure. Don't bother with TRY/CATCH/ROLLBACK, just put at the top of the procedure SET XACT_ABORT ON;, this guarantees a rollback on the event of an error.
Other notes:
Use proper types, length and precision on your SqlParameters, it will help with performance.
Do not block the thread with things like MessageBox while the connection is open. Log the exception and check it after. Or better, do what I did above and try/catch around the connection.
I have a project and when I try to run it and the data test is big I have always a connection timeout.
I added "sqlCmd.CommandTimeout = 3600;" but still not working.
What could am I doing wrong?
This is my code:
public void createCode(String ce, int ord, String beh, int wkd)
{
String strSql = "";
SqlCommand sqlCmd;
SqlConnection conexion = new SqlConnection(getConexion());
try
{
if (conexion.State != ConnectionState.Open)
conexion.Open();
//The insert works fine in sql server
strSql = "Insert into x with values";
sqlCmd = new SqlCommand(strSql, conexion);
sqlCmd.CommandTimeout = 3600;
sqlCmd.ExecuteScalar();
}
catch (Exception ex)
{
throw new Exception("Error creating Code. " + ex.Message);
}
finally
{
if (conexion.State == ConnectionState.Open)
conexion.Close();
}
}
You might need to set transaction timeout in your config file, like so;
<system.transactions>
<defaultSettings timeout="01:00:00" />
</system.transactions>
sqlCmd.ExecuteScalar() is not correct for your script, try using sqlCmd.ExecuteNonQuery() instead and remove timeout.
sqlCmd = new SqlCommand(strSql, conexion);
sqlCmd.ExecuteNonQuery();
Check each function, ExecuteScalar tries to return first value from a select, while ExecuteNonQuery does not retrieve any value, just gets num of rows affected.
Hope it helps!
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();
I need delete data in oracle 10g database from ASP.NET 2.0 web site.
Method DeleteMonthPlan I use on execute delete command. Problem is that this command is executing long time "in browser" and finally delete command is not executed. Maybe it waits on commit? What is root of problem?
This SQL command DELETE C_PPC_PLAN WHERE MFG_MONTH='VALUE' is OK.
MFG_MONTH column type is VARCHAR2(16)
First I need call method DeleteMonthPlan and than I need call InsertDatePlan.
private static void DeleteMonthPlan(string monthIndex)
{
try
{
using (var conn = new OracleConnection(GenerateConnectionString()))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = string.Format("DELETE C_PPC_PLAN WHERE MFG_MONTH='{0}'", monthIndex);
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
throw exception;
}
}
For example this method I use on insert and it is OK.
public void InsertDatePlan(DatePlan dp,
string monthIndex)
{
DeleteMonthPlan(monthIndex);
try
{
using (var conn = new OracleConnection(GenerateConnectionString()))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.Parameters.Add(":Site", OracleType.VarChar).Value = dp.Site;
cmd.Parameters.Add(":Week", OracleType.VarChar).Value = dp.MfgWeek;
cmd.Parameters.Add(":Month", OracleType.VarChar).Value = dp.MfgMonth;
cmd.Parameters.Add(":Year", OracleType.VarChar).Value = dp.MfgYear;
cmd.Parameters.Add(":Input", OracleType.Number).Value = dp.Input;
cmd.Parameters.Add(":Output", OracleType.Number).Value = dp.Output;
cmd.Parameters.Add(":LMUser", OracleType.VarChar).Value = dp.LmUser;
cmd.Parameters.Add(":PartNo", OracleType.VarChar).Value = dp.PartNo;
cmd.Parameters.Add(":PartNoDesc", OracleType.VarChar).Value = dp.PartNoDesc;
cmd.CommandText = string.Format("INSERT INTO C_PPC_PLAN (CREATE_TIME, SITE, MFG_DAY,MFG_WEEK,MFG_MONTH,MFG_YEAR,INPUT,OUTPUT,LM_TIME,LM_USER,PART_NO,PART_NO_DESC)"
+ " VALUES (to_date('{0}', 'dd-mm-yyyy hh24:mi:ss'), :Site ,to_date('{1}', 'dd-mm-yyyy hh24:mi:ss'),:Week,"
+ ":Month,:Year,:Input,:Output,to_date('{2}', 'dd-mm-yyyy hh24:mi:ss'),:LMUser,:PartNo,:PartNoDesc)"
, dp.CreateTime, dp.MfgDate, dp.LmTime);
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
throw exception;
}
}
I tried use transaction. I call this method on the bottom but is never finish it means that part
trans.Rollback(); or conn.Close(); is never executed.
private static void DeleteMonthPlan(string monthIndex)
{
var conn = new OracleConnection(GenerateConnectionString());
conn.Open();
OracleCommand cmd= conn.CreateCommand();
OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = trans;
try
{
cmd.CommandText = "DELETE C_PPC_PLAN WHERE MFG_MONTH='6'";
cmd.ExecuteNonQuery();
trans.Commit();
}
catch (Exception e)
{
trans.Rollback();
}
finally
{
conn.Close();
}
}
try
DELETE FROM C_PPC_PLAN WHERE MFG_MONTH='6'
BTW your code uses "literals" in some places instead of bind variables (params) which makes it vulnerable to SQL injection which is a really serious security problem!
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()
}
}