Local Database Insert query does nothing - c#

I am trying to insert a row into the database. Below is my query:
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
string query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.AddWithValue("#x", insert[2]);
command.Parameters.AddWithValue("#y", insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
conn.Close();
}
}
When I run it nothing happens (Also no SQL errors). What am I doing wrong? I am sorry if this is a stupid question, I am merely a beginner.
This should work (I have tested this with a select query that does work).

Have you tried storing the query on a stored procedure and calling it from C#? ... Thats actually easier than making the query via hard code inside the C# code ... Just create a stored procedure that does whatever you want it to do, then call it from C# and add the parameters. It should look something like this:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conection_String_s_Name"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.Your_Stored_Procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Input_Param_1", SqlDbType.VarChar, 18).Value = "C#_Parameter1";
cmd.Parameters.Add("#Input_Param_2", SqlDbType.VarChar, 45).Value = "C#Parameter_2";
cmd.Parameters.Add("#Input_Param_3", SqlDbType.VarChar, 45).Value = "C#Parameter_3";
cmd.Parameters.Add("#Input_Param_4", SqlDbType.Text).Value = "C#Parameter_4";
cmd.Parameters.Add("#Input_Param_5", SqlDbType.VarChar, 45).Value = "C#Parameter_5";
cmd.Parameters.Add("#Output_Parameter_1", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#Output_Parameter_2", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
"C#Output_Parameter_1" = "" + cmd.Parameters["#Output_Parameter_1"].Value;
"C#Output_Parameter_2" = "" + cmd.Parameters["#Output_Parameter_2"].Value;
Hope it helps.

My guess is that you have a type mismatch
If x, y are not int then substitute in the correct type
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
using (SqlCommand command = SqlCommand.CreateCommand())
{
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
command.Query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.Add("#x", SqlDbType.Int);
command.Parameters["#x"].Value = Int32.Parse(insert[2]);
command.Parameters.Add("#y", SqlDbType.Int);
command.Parameters["#y"].Value = Int32.Parse(insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
rowsRet = command.ExecuteNonQuery();
Console.WriteLine(rowsRet.ToString());
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
// op claims the insert is gone the next time the programs is run
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
}
}

Related

I have a listview with items which I want to insert into a SQL Server database

I want to save content of a listview into a SQL Server database.
I've tried the commented code but get an error
Must declare scalar variable #Description
Code:
private void btnFinish_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
try
{
foreach (ListViewItem item in lvregion.Items)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationSettings.AppSettings["conn"];
conn = new SqlConnection(connectionString);
comm = new SqlCommand(
"INSERT INTO Region (RegionDescription, Fname, Lname) " +
"VALUES (#RegionDescription, #Fname, #Lname)", conn);
//cmd.Parameters.AddWithValue("RegionDescription", item.Text.Trim());
//cmd.Parameters.AddWithValue("fname", item.SubItems[1].Text.Trim());
//cmd.Parameters.AddWithValue("lname", item.SubItems[2].Text.Trim());
cmd.Parameters.Add("RegionDescription", SqlDbType.VarChar,40);
cmd.Parameters.AddWithValue("RegionDescription", item.Text.Trim());
cmd.Parameters.Add("Fname", SqlDbType.VarChar,40);
cmd.Parameters.AddWithValue("Fname", item.SubItems[1].Text.Trim());
cmd.Parameters.Add("Lname", SqlDbType.VarChar,40);
cmd.Parameters.AddWithValue("Lname", item.SubItems[2].Text.Trim());
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Welcome to Stackoverflow,
First up, I wouldn't recommend creating a new connection within your foreach to add items to your table.
Here's what I'd recommend using instead:
try
{
string connectionString = ConfigurationSettings.AppSettings["conn"];
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd;
conn.Open();
string cmdString = #"INSERT INTO Region (RegionDescription, Fname, Lname)
VALUES (#RegionDescription, #Fname, #Lname)";
foreach (ListViewItem item in lvregion.Items)
{
cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.Add("#RegionDescription", SqlDbType.VarChar, 40).Value = item.Text.Trim();
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 40).Value = item.SubItems[1].Text.Trim();
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 40).Value = item.SubItems[2].Text.Trim();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
(Or at least this should have you on the right path.)

INSERT INTO Syntax error C# access database

When executing this query with parameters added as values, i get an error saying my syntax is wrong. I tried following multiple tutorials, looking up questions here is stack overflow, and when comparing, they seem the same, but mine does not seem to work.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\\Users\\fidyc\\OneDrive\\Desktop\\ProgrII.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT Product_Orders(order_ID,plankCount,thickness,width,height)VALUES(#order_ID, #plankCount, #thickness, #width, #height)");
cmd.Parameters.Add("#order_ID", OleDbType.Integer).Value = orderID;
cmd.Parameters.Add("#plankCount", OleDbType.Decimal).Value = plankCount;
cmd.Parameters.Add("#thickness", OleDbType.Decimal).Value = thickness;
cmd.Parameters.Add("#width", OleDbType.Decimal).Value = width;
cmd.Parameters.Add("#height", OleDbType.Decimal).Value = height;
cmd.Connection = con;
con.Open();
if (con.State == ConnectionState.Open)
{
/*try
{*/
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
/*}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
con.Close();
}*/
}
Edit: values are passed to the function
public static void Push(int orderID, decimal plankCount, decimal thickness, decimal width, decimal height)
{
The problem turned out to be the count column name, as sql has a count command, it needs to be
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,[count],thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
instead of
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,count,thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO bookRated "+
"([firstName], [lastName]) "+
"VALUES(#firstName, #lastName)";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#firstName", firstName),
new OleDbParameter("#lastName", lastName),
});
cmd.ExecuteNonQuery();
}

Insert in c# using npgsql

When I'm trying to execute an insert query with npgsqlcommand to postgres in c#, the execution of the program is suspend to cmd.ExecuteNonQuery();
Here's my code
public void Insert(Mouvement mvt)
{
NpgsqlConnection conn = null;
NpgsqlCommand cmd = null;
try
{
conn = UtilDB.GetConnection();
String sql = "INSERT INTO MOUVEMENT(ID_AERONEF,ID_PF,ID_ESCALE,DATE,SENS,NVOL,PISTE,BLOC,PAXC,PAXY,PAXBB,PAXEXO," +
"TRANSITDIRECT,TRANSITRI,TRANSITRRLC,CONTINU,PN,FRETPAYANT,FRETGRATUIT,BAGAGE,POSTE,MODE,BALISAGE,OBSERVATION) "+
"VALUES (:id_aeronef,:id_pf,:id_escale,:date,:sens,:nvol,:piste,:bloc,:paxc,:paxy,:paxbb,:paxexo," +
":transitdirect,:transitri,:transitrrlc,:continu,:pn,:fretpayant,:fretgratuit,:bagage,:poste,:mode,:balisage,:observation)";
conn.Open();
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.Add("id_aeronef", mvt.Aeronef.Id);
cmd.Parameters.Add("id_pf", mvt.Plateforme.Id);
cmd.Parameters.Add("id_escale", mvt.Escale.Id);
cmd.Parameters.Add("date", mvt.Date);
cmd.Parameters.Add("sens", mvt.Sens);
cmd.Parameters.Add("nvol", mvt.Nvol);
cmd.Parameters.Add("piste", mvt.Piste);
cmd.Parameters.Add("bloc", mvt.Bloc);
cmd.Parameters.Add("paxc", mvt.PaxC);
cmd.Parameters.Add("paxy", mvt.PaxY);
cmd.Parameters.Add("paxbb", mvt.PaxBB);
cmd.Parameters.Add("paxexo", mvt.PaxExo);
cmd.Parameters.Add("transitdirect", mvt.TransitDirect);
cmd.Parameters.Add("transitri", mvt.TransitRI);
cmd.Parameters.Add("transitrrlc", mvt.TransitRRLC);
cmd.Parameters.Add("continu", mvt.Continu);
cmd.Parameters.Add("pn", mvt.Pn);
cmd.Parameters.Add("fretpayant", mvt.FretPayant);
cmd.Parameters.Add("fretgratuit", mvt.FretGratuit);
cmd.Parameters.Add("bagage", mvt.Bagage);
cmd.Parameters.Add("poste", mvt.Poste);
cmd.Parameters.Add("mode", mvt.Mode);
cmd.Parameters.Add("balisage", mvt.Balisage);
cmd.Parameters.Add("observation", mvt.Observation);
cmd.Prepare();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(cmd!=null) cmd.Dispose();
if(conn!=null) conn.Close();
}
}
Finally, it was a problem of type: I have character(1) in database but String(10) in C#

"Procedure or function expects parameter which was not supplied."

I'm trying to execute a stored procedure and print the output, but when I run the below code I'm getting error like "Procedure or function 'SPInsertLocal' expects parameter '#RES', which was not supplied."
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type", con);
try
{
con.Open();
cmd.CommandTimeout = 150;
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
SqlParameter output = new SqlParameter("#RES", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
con.Close();
int id = Convert.ToInt32(output.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
What I'm doing wrong here?
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type,#RES", con);
I was not passing the parameter , fixed the issue
You can refactor the code as follows where the using statement is used for the auto management of connection closing and avoid hardcoding Execute statement in c# code which is a bad practice
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
try
{
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
var output = cmd.Parameters.Add("#RES" , SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int id = Convert.ToInt32(output.Value);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Connect to SQL Server in C#

I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}

Categories

Resources