I'm a new coder trying to code C# to insert data into sqlworkbench database. Having alot of problems. Looking for any help. Thanks.
private void enterbutton_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=mydb;";
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into garden(idGarden) VALUES (#idGarden)");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#idGarden", gardentextBox.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
SqlCommand cmd1 = new SqlCommand("insert into rainfall(aveRainfall) VALUES (#aveRainfall)");
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#aveRainfall", aveRaintextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into seat(idSeat) VALUES (#idSeat)");
cmd2.Connection = conn;
cmd2.Parameters.AddWithValue("#idSeat", seatIDtextBox.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
SqlCommand cmd3 = new SqlCommand("insert into temperature(currentTemp) VALUES (#currentTemp)");
cmd3.Connection = conn;
cmd3.Parameters.AddWithValue("#currentTemp", currentTemptextBox.Text);
cmd3.ExecuteNonQuery();
cmd3.Parameters.Clear();
conn.Close();
}
You didn't connect your SqlCommand's with your MySqlConnection. And I think they should MySQLSqlCommand instead of SqlCommand.
You can assing their .Connection properties to your MySqlConnection. Like;
cmd.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd4.Connection = conn;
And you try to execute your cmd only. I think you should execute your all others commands like cmd2, cmd3 and cmd4..
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
And could be better to use using statement to dispose your database connections..
using(MySqlConnection conn = new MySqlConnection(myConnectionString))
using(MySQLCommand cmd = conn.CreateCommand())
{
//
}
Also always prefer to use Add() instead of AddWithValue().
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
Related
I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}
First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=MYDATASOURCE";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID, #IngredientNaam";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
I want to insert data to the tables Voorraad and Ingredient. In the tables Voorraad there must IngredientID, AantalInVoorraad, MinimumVoorraad and Categorie be in the table after instert.
In the table Ingredient there must be an new Ingredientnaam be made. When i filling in the text boxes and after hitting the button insert i get the error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#MinimumVoorraad'.'
Please help me!
I've edited to this:
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID,
#IngredientNaam)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
Does anybody know maybe another way to insert data to multiple tables in the datbase?? I've searched the whole internet for an answer but i can't find the right solution.
Introducing ASP.NET Web Pages - Entering Database Data by Using Forms
cmd.CommandText = "Insert into [Voorraad] (IngredientID, AantalInVoorraad, MinimumVoorraad) values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)";
and
cmd.CommandText = "insert into [Ingredient] (IngredientID, IngredientNaam) values(#IngredientID, #IngredientNaam)";
Your insert statements are missing the closing bracket for the values.
Add a using Statement for the SQlConnection and SQLCommand, will make it easier to read and debug.
using (SqlConnection con = new SqlConnection(#"Data Source=MYDATASOURCE"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(
"Insert into [Voorraad] values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.ExecuteNonQuery();
}
using(SqlCommand cmd = new SqlCommand(
"insert into [Ingredient] values(#IngredientID, #IngredientNaam)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
}
}
may be i am tired but any body can say what is the poblem?
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='c:\users\deltagare\documents\visual studio 2015\Projects\School\School\school.mdf';Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'schoolDataSet.student' table. You can move, or remove it, as needed.
//this.studentTableAdapter.Fill(this.schoolDataSet.student);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from student";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
student = new StudentController();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
studentGridView.DataSource = dt;
conn.Close();
}
You have either to use the SqlCommand(string,SqlConnection) overload, or set the SqlCommand.Connection property:
SqlCommand cmd = new SqlCommand("select * from student",conn);
Or
cmd.Connection=conn;
you have to assign the connection to the command before you execute it:
cmd.Connection = conn
I need to run several queries inside one function. My working code for single query is as below:
C# Code:
try
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.0.0.24)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DEVL)));User Id=aaziz;Password=123211;";
con.Open();
string cmdQuery = "Insert into M.person (RED_NO, USED_FLAG) VALUES ('12', '0')";
OracleCommand cmd = new OracleCommand(cmdQuery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
How to modify it to accommodate multiple SQL queries?
try
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.0.0.24)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DEVL)));User Id=aaziz;Password=123211;";
con.Open();
string cmdQuery = "Insert into M.person (RED_NO, USED_FLAG) VALUES ('12', '0')";
OracleCommand cmd = new OracleCommand(cmdQuery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
con.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
I've not used basic SQL commands for a while and I'm trying to pass a param to a sproc and the run it. However when I run the code I get a "Not Supplied" error.
Code:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.Parameters.Add(new SqlParameter("#ID", itemId));
conn1.Open();
cmd1.ExecuteNonQuery();
I'm not really sure why this would fail. Apologies for the basic question, but I'm lost!
Thanks in advance.
You should set the CommandType to StoredProcedure, set the connection and use Parameters.AddWithValue("#ID", itemID)
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Connection = conn1;
cmd1.Parameters.AddWithValue("#ID",itemID);
conn1.Open();
cmd1.ExecuteNonQuery();
If you want to use Parameters.Add() (which is obsolete), here is how you do it (you need to pass the type too)
cmd1.Parameters.Add("#ID", SqlDbType.Int); //string maybe, I don't know
cmd1.Parameters["#ID"].Value = itemID;
This should work:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
And to make your code even better, put your SqlConnection and SqlCommand into using statements, so that they'll be freed automatically at the end of the using block:
using(SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr()))
{
using(SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
}