I'm trying to insert some data read from XML files into my database. The problem is that it only executes one prepared statement (the first one i defined) and this causes errors.
This works:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_gestiuni ([denumire],[id_ra]) Values(#denumire,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
This does not work anymore:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_active ([denumire],[gestiune],[utilizator],[tip_activ],[nr_invetar],[categorie_activ],[patrimoniu],[id_ra]) Values(#denumire,#gestiune,#utilizator,#tip_activ,#nr_invetar,#categorie_activ,#patrimoniu,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter gestiuneParam = new SqlCeParameter("#gestiune", SqlDbType.Int);
gestiuneParam.Value = gestiune;
cmd.Parameters.Add(gestiuneParam);
SqlCeParameter utilizatorParam = new SqlCeParameter("#utilizator", SqlDbType.Int);
utilizatorParam.Value = utilizator;
cmd.Parameters.Add(utilizatorParam);
SqlCeParameter nrInventarParam = new SqlCeParameter("#nr_inventar", SqlDbType.NVarChar);
nrInventarParam.Value = nrInventar;
cmd.Parameters.Add(nrInventarParam);
SqlCeParameter categorieActivParam = new SqlCeParameter("#categorie_activ", SqlDbType.NVarChar);
categorieActivParam.Value = categorieActiv;
cmd.Parameters.Add(categorieActivParam);
SqlCeParameter patrimoniuParam = new SqlCeParameter("#patrimoniu", SqlDbType.Int);
patrimoniuParam.Value = patrimoniu;
cmd.Parameters.Add(patrimoniuParam);
SqlCeParameter tipActivParam = new SqlCeParameter("#tip_activ", SqlDbType.Int);
tipActivParam.Value = tipActiv;
cmd.Parameters.Add(tipActivParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
I get this exception:
The column name is not valid [ Node name (if any) = ,Column name = gestiune ]
This happens because it tries to insert in the previous table (from the previous prepared statement). This is insane, I haven't found any solution to this.
What I see is the parameter #nr_inventar does not exists in your command text (you have #nr_invetar there). Also if you really need to prepare the command before executing, you should set a size for all nvarchar parameters, like you did for #denumire.
Related
I have a listview which is adding some products in the database. If i insert one product, it works perfectly. The problem with this code is the cmd2.Parameters.Clear(); If i insert more than one product in the form listview, it only sends the last one to the database. How can i do to insert all products, because it seems that if i don't use parameters.clear, it's not working at all. There is no error thrown, it just does not insert products.
This is the code:
private void InsertOrder_Click(object sender, EventArgs e)
{
//---------------Inserare client--------------------
SqlCommand cmd = new SqlCommand("InsertClients", con);
cmd.CommandType = CommandType.StoredProcedure;
if (TextBoxClientNou.Enabled)
{
cmd.Parameters.AddWithValue("#NumeClient", TextBoxClientNou.Text);
}
else
{
cmd.Parameters.AddWithValue("#NumeClient", ClientExistent.Text);
}
var IDClientParameter = cmd.Parameters.Add("#IDClient", SqlDbType.Int);
IDClientParameter.Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
var IDClient = (int)IDClientParameter.Value;
con.Close();
//--------------------Inserare Produse------------------
SqlCommand cmd2 = new SqlCommand("InsertProducts", con);
cmd2.CommandType = CommandType.StoredProcedure;
foreach (ListViewItem item in ListaProduse.Items)
{
cmd2.Parameters.Clear(); //Problem here
cmd2.Parameters.AddWithValue("#Denumire", item.Text);
cmd2.Parameters.AddWithValue("#Cantitate", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#Dimensiuni", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#Comentarii", item.SubItems[1].Text);
}
var IDProductParameter = cmd2.Parameters.Add("#IDProdus", SqlDbType.Int);
IDProductParameter.Direction = ParameterDirection.Output;
con.Open();
cmd2.ExecuteNonQuery();
var IDProdus = (int)IDProductParameter.Value;
con.Close();
//--------------------Inserare comanda-------------------
SqlCommand cmd3 = new SqlCommand("InsertOrders", con);
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.Parameters.AddWithValue("#IDClient", IDClient);
cmd3.Parameters.AddWithValue("#IDProdus", IDProdus);
cmd3.Parameters.AddWithValue("#DataInceput", dateTimePicker1.Text);
cmd3.Parameters.AddWithValue("#DataSfarsit", dateTimePicker2.Text);
cmd3.Parameters.AddWithValue("#Facturata", factstatus);
cmd3.Parameters.AddWithValue("#Livrata", livstatus);
con.Open();
cmd3.ExecuteNonQuery();
con.Close();
you have to execute the query inside your loop, cause you're adding parameters in the loop (if two ListViewItem so 8 parameters), that's why you're getting this error.
foreach (ListViewItem item in ListaProduse.Items)
{
SqlCommand cmd2 = new SqlCommand("InsertProducts", con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#DenProd", item.Text);
cmd2.Parameters.AddWithValue("#ProdQuant", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#ProdSize", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#ProdComm", item.SubItems[1].Text);
var IDProductParameter = cmd2.Parameters.Add("#ProdID", SqlDbType.Int);
IDProductParameter.Direction = ParameterDirection.Output;
con.Open();
cmd2.ExecuteNonQuery();
var IDProdus = (int)IDProductParameter.Value;
con.Close();
}
You are adding the parameters without clearing the originals. You can either use Parameters.Clear() or you can change the Value of existing parameters. You then need to execute the command within the loop.
Note that you must use using blocks to dispose the connection. And if you do so, the connection will be closed automatically
Specify the parameter types and lengths explicitly
var listIds = new List<int>();
using (var con = new SqlConnection(YourConnString))
using (var cmd2 = new SqlCommand("InsertProducts", con) { CommandType = CommandType.StoredProcedure })
using (var cmd3 = new SqlCommand("InsertOrders", con) { CommandType = CommandType.StoredProcedure })
{
cmd2.Parameters.Add("#DenProd", SqlDbType.NVarChar, 50);
cmd2.Parameters.Add("#ProdQuant", SqlDbType.NVarChar, 50);
cmd2.Parameters.Add("#ProdSize", SqlDbType.NVarChar, 50);
cmd2.Parameters.Add("#ProdComm", SqlDbType.NVarChar, 50);
var IDProductParameter = cmd2.Parameters.Add("#ProdID", SqlDbType.Int);
IDProductParameter.Direction = ParameterDirection.Output;
cmd3.Parameters.Add("#IDClient", SqlDbType.Int).Value = IDClient;
cmd3.Parameters.Add("#IDProdus", SqlDbType.Int);
cmd3.Parameters.Add("#DataInceput", SqlDbType.DateTime).Value = dateTimePicker1.Text;
cmd3.Parameters.Add("#DataSfarsit", SqlDbType.DateTime).Value = dateTimePicker2.Text;
cmd3.Parameters.Add("#Facturata", SqlDbType.NVarChar, 50).Value = factstatus;
cmd3.Parameters.Add("#Livrata", SqlDbType.NVarChar, 50).Value = livstatus;
con.Open();
foreach (ListViewItem item in ListaProduse.Items)
{
cmd2.Parameters["#DenProd"].Value = item.Text;
cmd2.Parameters["#ProdQuant"].Value = item.SubItems[1].Text;
cmd2.Parameters["#ProdSize"].Value = item.SubItems[1].Text;
cmd2.Parameters["#ProdComm"].Value = item.SubItems[1].Text;
cmd2.ExecuteNonQuery();
var IDProdus = (int)IDProductParameter.Value; // do something with this value
cmd3.Parameters.AddWithValue("#IDProdus", IDProdus);
cmd3.ExecuteNonQuery();
}
}
I must say, ideally you should use either a Table Valued parameter or SqlBulkCopy to do this in bulk, it will not be performant for large numbers of rows.
I tried below code,
ora.Open();
OracleCommand cmd = new OracleCommand() ;
cmd.Connection= ora;
cmd.CommandTimeout = 0;
cmd.CommandText = "update test set name= :name";
OracleParameter name = new OracleParameter("name", OracleDbType.Varchar2);
cmd.BindByName = true;
name.Value = "test";
cmd.Parameters.Add(a);
cmd.ExecuteNonQuery();
ExecuteNonQuery does not work and no errors. What's wrong?
I work with Visual Studio 2012 and Oracle Express 11g
You are adding a parameter named a instead the one you've created. Try this:
ora.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = ora;
cmd.BindByName = true;
cmd.CommandText = "update test set name = :name";
OracleParameter name = new OracleParameter("name", OracleDbType.Varchar2);
name.Value = "test";
cmd.Parameters.Add(name); // add the name parameter, not "a" object.
cmd.ExecuteNonQuery();
}
Maybe you are missing the Prepare function?
try adding
cmd.Prepare(); just after cmd.Parameters.Add(name);
I am using mySQL with .net 4.5 to do typical CRUD commands.
I have an issue wit a parameter which is called 'Message' (Chat application). It seems the text inserted into the database is being cut off at 200 bytes.
I have tried multiple data types for the column. Currently it is TEXT, I have tried LONGTEXT and varchar(1000) etc; but still, it gets cut off at 200 bytes.
What is going on?
MySqlConnection conn = new MySqlConnection(ConnectionString());
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Parameters.Clear();
cmd.CommandText = "createStaffMessage";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#sessionID", sessionID);
cmd.Parameters["#sessionID"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#chatID", chatId);
cmd.Parameters["#chatID"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#message", message);
cmd.Parameters["#message"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#byStaff", byStaff);
cmd.Parameters["#byStaff"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#staffId", staffId);
cmd.Parameters["#staffId"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#dateTimeString", DateTime.Now.ToLongTimeString() + " (NZ Time)");
cmd.Parameters["#dateTimeString"].Direction = ParameterDirection.Input;
cmd.Connection = conn;
MySqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string[] newMessageDetails = new string[2];
newMessageDetails[0] = rdr[0].ToString();
newMessageDetails[1] = rdr[1].ToString();
conn.Close();
return newMessageDetails;
I have two Databases Movies(id, name) and SessionsCinema(id, SessionTime, movie, hall, price).
id - is auto increment row.
I work in ado.net Disconnected mode with ms sql database.
I want to save settings to sql table.
Changes to table "Movies" is ok, but with table "SessionsCinema" there are some errors.
//connection start
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "MYPC\SQLEXPRESS";
builder.InitialCatalog = "Cinema";
builder.IntegratedSecurity = true;
SqlConnection conn = new SqlConnection(builder.ConnectionString);
//connection end
//Movies start
SqlCommand inscmd = new SqlCommand();
inscmd.CommandText = "Insert into Movies (name) values(#name); select id = ##IDENTITY from Movies";
inscmd.Connection = conn;
inscmd.Parameters.Add("#name", SqlDbType.NVarChar, 250, "name");
SqlDataAdapter adapter = new SqlDataAdapter(inscmd);
adapter.InsertCommand = inscmd;
adapter.Update(Movies);
//Movies end
//SessionsCinema start
inscmd = new SqlCommand();
inscmd.CommandText = "Insert into SessionsCinema (SessionTime, movie, hall, price) values(#SessionTime, #movie, #hall, #price); select id = ##IDENTITY from SessionsCinema";
inscmd.Connection = conn;
inscmd.Parameters.Add("#SessionTime,#movie,#hall,#price", SqlDbType.NVarChar, 250, "SessionTime,movie,hall,price");
adapter = new SqlDataAdapter(inscmd);
adapter.InsertCommand = inscmd;
adapter.Update(SessionsCinema);
//SessionsCinema end
You must look at closer to SqlParameterCollection.Add signature.
//SessionsCinema start
inscmd = new SqlCommand();
inscmd.CommandText = "Insert into SessionsCinema (SessionTime, movie, hall, price) values(#SessionTime, #movie, #hall, #price); select id = ##IDENTITY from SessionsCinema";
inscmd.Connection = conn;
inscmd.Parameters.Add("#SessionTime, SqlDbType.NVarChar, 250).Value = SessionTime;
inscmd.Parameters.Add("#movie", SqlDbType.NVarChar, 250).Value = movie;
inscmd.Parameters.Add("#hall", SqlDbType.NVarChar, 250).Value = hall;
inscmd.Parameters.Add("#price", SqlDbType.NVarChar, 250).Value = price;
adapter = new SqlDataAdapter(inscmd);
adapter.InsertCommand = inscmd;
adapter.Update(SessionsCinema);
//SessionsCinema end
Your first command works because it has only one parameter and you define one .Add method for it. That's ok.
But your second command has 4 parameter and you can't add 4 parameter in just one .Add method.
You need to add them seperatly with SqlParameterCollection.AddWithValue like;
inscmd.Parameters.AddWithValue("#SessionTime, SessionTime);
inscmd.Parameters.AddWithValue("#movie", movie);
inscmd.Parameters.AddWithValue("#hall", hall);
inscmd.Parameters.AddWithValue("#price", price);
This line is wrong:
inscmd.Parameters.Add("#SessionTime,#movie,#hall,#price", SqlDbType.NVarChar, 250, "SessionTime,movie,hall,price");
You need a separate Parameters.Add() call for each of the parameters in that list. It should look something like this:
inscmd.Parameters.Add("#SessionTime", SqlDbType.NVarChar, 250).Value = SessionTime;
inscmd.Parameters.Add("#movie", SqlDbType.Int).Value = movie;
inscmd.Parameters.Add("#hall", SqlDbType.Int).Value = hall;
inscmd.Parameters.Add("#price", SqlDbType.Money).Value = price;
Also, check your parameter from your first command. It looks like you made the same mistake there.
I have a stored procedure with an output parameter. How do I read this value using C# code?
I assume you use ADO.NET? If so, the SqlParameter class has the property "Direction". Set direction to output and after the query has executed you read the value from that parameter.
Something like this:
using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("#pkid", SqlDbType.Int);
parm.Value = 1;
parm.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm);
SqlParameter parm2 = new SqlParameter("#ProductName", SqlDbType.VarChar);
parm2.Size = 50;
parm2.Direction = ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm2);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}