I'm creating a small c# application using VS local database these are my commands for inserting its not showing any error but the fields are not inserted in the database.
public partial class Form1 : Form
{
SqlCeConnection cn=new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
public Form1()
{
InitializeComponent();
cn.Open();
SqlCeCommand cmd;
string sql = "insert into sales values (#item, #price)";
try
{
cmd = new SqlCeCommand(sql, cn);
cmd.Parameters.AddWithValue("#item", "7777");
cmd.Parameters.AddWithValue("#price"," 2");
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
}
Just one more question when deploying this application to the user should I install anything on the client machine??
Try something like this
//include column names
string sql = "insert into sales(Item,Price) values (#item, #price)";
try
{
cmd = new SqlCeCommand(sql, cn);
cmd.Parameters.AddWithValue("#item", 7777); //int instead of string
cmd.Parameters.AddWithValue("#price", 2); //int instead of string
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
Related
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.)
Query with parameters works perfectly in ms access database. But when I supply the same parameters from C# winforms application it returns no records.
If the parameter is passed to the query then it will use that parameter in where clause, otherwise it will retrieve all records.
bus table sample data:
Ms-Access Query:
PARAMETERS parPlateNo Text ( 255 );
SELECT bus.*
FROM bus
WHERE (((bus.plateNo) Like IIf(IsNull([parPlateNo]), True ,"%" & [parPlateNo] & "%")));
C# Code:
using (OleDbConnection conn = new OleDbConnection(myGlobals.connString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "qryBus";
if(plateNo == "")
cmd.Parameters.AddWithValue("?", DBNull.Value);
else
cmd.Parameters.AddWithValue("?", plateNo);
adapter.SelectCommand = cmd;
dsDetails = new DataSet();
adapter.Fill(dsDetails, "details");
}
}
}
PlateNo is a text column.
Remarks: If I remove the like statement in ms access query and run the same code in C#, it will run perfectly and retrieve all the records in table.
After that, I display the data in datagridview using bindingsource.
Why this is happening?
You using oleDB. You have to change that query and use % as wild cards. DAO, and native Access you use *, but for ADO, or oleDB, you have to use % as the wild cards.
Here are a couple of examples that should help you get this up and running.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("insert into [dbo].[Student] values(#a,#b,#c)", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("#b", textBox2.Text);
cmd.Parameters.AddWithValue("#c", textBox3.Text);
con.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submited");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
AND
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("select * from student where sid=#a", con);
cmd.Parameters.AddWithValue("#a",int.Parse(comboBox1.SelectedItem.ToString()));
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
textBox1.Text = dr["sid"].ToString();
textBox2.Text = dr["fname"].ToString();
textBox3.Text = dr["lname"].ToString();
//label1.Text = dr["cdate"].ToString();
}
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
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#
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();
}
}
}
I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}