I'm trying to put anything into my DB. Message Box is showing that I did put 1 row to DB, but when I check it - nothing happened.
Anybody know the cure?
SqlCeConnection cn = new SqlCeConnection(#"Data Source = Database1.sdf");
try
{
cn.Open();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
SqlCeCommand cm = new SqlCeCommand("INSERT INTO Sentences (Sentence) VALUES ('Sentence')", cn);
//cm.Parameters.AddWithValue("#Sentence", "Any sentence");
try
{
int rowsAffected = cm.ExecuteNonQuery();
MessageBox.Show((rowsAffected.ToString()));
}
catch (Exception)
{
MessageBox.Show("Insertion Failed");
}
cn.Close();
Try some nice and easy code.
using (SqlCeConnection con = new SqlCeConnection(strConn))
{
try
{
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("insert into Table (column1,Column2) values (#Val1, #val2)", con))
{
cmd.Parameters.AddWithValue("#Val1", value1);
cmd.Parameters.AddWithValue("#Val2", value2);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
con.Close();
} catch (Exception ex){
//handle any exception here
}
}
suggest you to use a full path to your database file in your connection string.
complete example like =
#"Data Source=C:\Users\MYPC\Documents\Visual Studio
2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist
Security Info=False;"
Well explained here !!
Related
I am working on a windows form project with a sql database I want to write some data but I couldn't. (the code doesn't give any error however no data is written.
The code below is the place where I want to write the data:
public static string stringConnection = #"Data Source=(localdb)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\POS.mdf; Integrated Security=True";
try
{
mySql = string.Empty;
mySql += "INSERT INTO Journal (Date) VALUES (" + "'"+ caisse + "'"+")" ;
connection.exsql(mySql);
}
catch(Exception exx)
{
MessageBox.Show(exx.ToString());
}
and here is the connection.exsql method:
public static void exsql(string sql)
{
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = default(SqlDataAdapter);
try
{
connection.ConnectionString = stringConnection;
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
connection.Close();
//connection = null;
}
catch (Exception ex)
{
MessageBox.Show("Fatal sql error: " + ex.Message, "Sql Server connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You want to use the sqlCommand and execute .ExecuteNonQuery() to do an INSERT or UPDATE.
More info here.
Also, use parameterization (an example is shown in the link above), otherwise, you open yourself up to SQL injection and your code will fail if your variable contains a single quote.
Less code
private bool exsql(string query)
{
using(var conn = new SqlConnection(ConnectionString.path))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
return command.ExecuteNonQuery() == 0 ? false : true;
}
}
SqlConnection con;
SqlCommand cmd;
public bool exsql(string query)
{
try {
con = null;
con = new SqlConnection(ConnectionString.path);
cmd = new SqlCommand(query, con);
con.Open();
var rowEffected = cmd.ExecuteNonQuery();
con.Close();
if(rowEffected>0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception occurred !",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
You can execute your query by ExecuteNonQuery() function
Not inserting data into database and not getting any error
private void add_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(global::Employees.Properties.Settings.Default.Database1ConnectionString);
try
{
string query = "INSERT INTO Employee (username,password,city,phone)";
query += " VALUES (#username,#password,#city,#phone)";
SqlCommand myCommand = new SqlCommand(query, connection);
myCommand.Parameters.AddWithValue("#username", username.Text);
myCommand.Parameters.AddWithValue("#password", password.Text);
myCommand.Parameters.AddWithValue("#city", listBox.Text);
myCommand.Parameters.AddWithValue("#phone", phone.Text);
connection.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("Success add Employee");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally{
connection.Close();
}
}
Try this way will work as expected
string connectionString = #"data source=WS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";//Replace Your connection string
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Employee (username,password,city,phone) VALUES (#username,#password,#city,#phone)", _connection))
{
command.Parameters.AddWithValue("#username", "testuser");
command.Parameters.AddWithValue("#password", "pass");
command.Parameters.AddWithValue("#city", "TestCity");
command.Parameters.AddWithValue("#phone", "TestPhone");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Note:
Check database Name on connection string,
table name and given parameter for example #username should be same,
Make sure your syntax is correct.
Let me know if you have anymore concern.
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#
For some reason result is always -1 and nothing get added to the database. I executed the query in SQL Server and it runs fine. I don't get any exception whatsoever and I don't use any stored procedure.
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=RAINBOW;Integrated Security=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO ItemDetails.item(description,category_id) VALUES (#item_desc,#cat_id)", con);
cmd.Parameters.AddWithValue("#item_desc", txtitemdesc.Text);
cmd.Parameters.AddWithValue("#cat_id", GetCategoryID());
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
Edit
int GetCategoryID()
{
int cat_id = 0;
cmd = new SqlCommand("SELECT category_id FROM ItemDetails.category WHERE category_desc=#cat_desc", con);
con.Open();
cmd.Parameters.AddWithValue("#cat_desc", cboCategory.Text);
reader = cmd.ExecuteReader();
while (reader.Read())
{
cat_id = int.Parse(reader["category_id"].ToString());
}
reader.Close();
con.Close();
return cat_id;
}
If possible then don't use AddWithValue(). Actually when you are not providing type explicitly, it will try to convert implicitly and sometimes the implicit conversion may not be the most optimal of conversions. You can find some more discussion in this link.
And most important thing is don't forget to clear parameters before assign, by using this line.
cmd.Parameters.Clears();
Check below code.
string sqlQuery = "INSERT INTO ItemDetails.item(description,category_id) VALUES (#item_desc,#cat_id)";
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clears(); // Add this same line in your getcategory function.
cmd.Parameters.Add("#item_desc", SqlDbType.VarChar, 1000).Value = txtitemdesc.Text;
cmd.Parameters.Add("#cat_id", SqlDbType.Int).Value = GetCategoryID();
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
}
i'm realising a litel program with windows forms c#, that saves data in ms ACCESS database.
i write this code
OleDbConnection connect = new OleDbConnection();
private void button1_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb";
string fname = textBox1.Text;
string lname = textBox2.Text;
connect.Open();
OleDbCommand cmd = new OleDbCommand(" INSERT INTO user ([nom],[prenom]) VALUES (#fname,#lname)",connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("erreur" + ex.Source);
connect.Close();
}
}
else
{
MessageBox.Show("probleme connection");
}
}
and i got this error when executing it
"error in insert methode"
i have not idea the error in insert request. have you an idea
Try this. I added the using-statements and [ ]-brackets to the query string.
string fname = textBox1.Text;
string lname = textBox2.Text;
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb"))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO [user] ([nom],[prenom]) VALUES (#fname,#lname)", conn))
{
try
{
conn.Open();
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
}
catch (Exception ex) { MessageBox.Show("Erreur" + ex.Source); }
finally { if (conn.State == ConnectionState.Open) { conn.Close(); } }
}
The OLE DB .NET Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.So, Try to use ? instead of named parameter. for example.
INSERT INTO [user] ([nom],[prenom]) VALUES (?,?)
comand.Parameters.Add("nom", OleDbType.VarChar).Value = fname;