SQL parameters not working - c#

This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command

You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}

Related

C# Connection must be valid and open Mysql

is there something wrong with my codes. I already try another codes but the problem is still the same. I've been solving this error for a couple of weeks now, and i can't figure it out how to solve it. And also I already try some another code but the problem is still the same.
I want to save a multiple row from dataGrid to my database.
here's the codes that i use to save a multiple row
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conString = new MySqlConnection("datasource = localhost; port = 3306; Initial catalog = dbnewsystem; username = root;password = 1234");
MySqlCommand command1 = new MySqlCommand("INSERT INTO purchaseorder (orNo, ProdNo, Quantity, total)" +
"VALUES(#ORNo,#ProductNo,#quantity,#total )", conString);
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
conString.Open();
command1.ExecuteNonQuery();
command1.Connection = conString;
conString.Close();
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "pos_save";
if (command1.ExecuteNonQuery() == 1)
{
MessageBox.Show("saved");
}
else
{
MessageBox.Show("Sorry Nothing to be Update");
}
conString.Close();
}
change sequence
command1.Connection = conString;
command1.ExecuteNonQuery();
You have implemented wrong sequence:
...
conString.Open(); // Connection opened
command1.ExecuteNonQuery(); // Try executing (fail)
command1.Connection = conString; // Connection assigned
Change to
conString.Open(); // Connection opened
command1.Connection = conString; // Connection assigned
command1.ExecuteNonQuery(); // Try executing (fail)
A better design is
// Wrap IDisposable into using
using (MySqlConnection conString = new MySqlConnection("...")) {
conString.Open();
// Make SQL Readable
string sql =
#"INSERT INTO purchaseorder(
orNo,
ProdNo,
Quantity,
total)
VALUES(
#ORNo,
#ProductNo,
#quantity,
#total)";
// Wrap IDisposable into using
using (MySqlCommand command1 = new MySqlCommand(sql, conString)) {
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
command1.ExecuteNonQuery();
}
}

C# simple code to write an INSERT query is giving an exception

I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}

Trying to use an INSERT method but not working

i'm trying to use an insert method in my studentHelperClass, I am trying to activate it on a button click on my form, I don't know how to make it work with a text box, so if someone could help with that, that would be great.
This is my method:
public static void insertStudent()
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (#personID)";
cmd.Parameters.AddWithValue("#personID", "123345667788");
prevID(conn, cmd);
}
and this is my form:
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent();
}
EDIT:
private static void prevID(MySqlConnection conn, MySqlCommand cmd)
{
conn.Open();
cmd.ExecuteNonQuery();
long studentNumber = (long)cmd.LastInsertedId;
Console.Write("previous id {0} ", studentNumber);
Console.ReadLine();
conn.Close();
}
Considering the information, assuming that your prevId(conn,cmd) is calling ExecuteNonQuery, you will still need to set the cmd.CommandText to be equal to your myInsertSql (as other answers have pointed out).
To answer your question though,
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(studentIdTextBox.Text);
}
public static void insertStudent(string studentId)
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (?personID)";
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("?personID", studentId);
prevID(conn, cmd);
}
Ive also assumed your studentId is a string. If the database has it as a bigint, you will have to do the proper long.TryParse() call.
You need to set cmd.CommandText as myInsertSQL
and also need to call cmd.ExecuteNonQuery()
string sql = "INSERT INTO person (personID) VALUES (#personID)";
using (MySqlConnection conn = connection())
using (MySqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
}
You must assign your string variable, 'myInsertSQL' to cmd.CommandText, and then call, cmd.ExecuteNonQuery();
I.e.
cmd.CommandText = myInsertSQL;
cmd.ExecuteNonQuery();
cmd.Dispose();
Always call 'Dispose();' when finished so the .net Garbage Collection can cleanup and manage resources.
You don't use the myInsertSQL string at all, you just set it. You have to set the string as the command text by cmd.CommandText = myInsertSQL and you have to call the method cmd.ExecuteNonQuery().

Read data from Access Database into listbox

Can someone tell me how to fix this error?
SqlCommand cmd = new SqlCommand(sqlCmd, conn)
--> conn: Aurgument type 'System.Data.OleDb.OleDbConnection' is not assignable to parameter type 'System.Data.SqlClient.SqlConnection'.
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
SqlCommand cmd = new SqlCommand(sqlCmd, conn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You're mixing up Sql and OleDb
Use OleDbCommand instead of SqlCommand
and use OleDBDataReader instead of SqlDataReader
For example:
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);
using (OleDBDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You are using SqlCommand/etc which requires the use of SqlConnection object instead of OleDbConnection.
Is it a SQL database you are connecting to? If so use SqlConnection instead
Edit: Obviously not, reading the connection string ... :D

Trouble Deleting entries from an access database using C# (Visual Studio)

I'm Having some trouble deleting an entry on my database.
I can insert data, but i can't delete them.
I have a 2 variables database, and i want to manage those data.
but when i debug the program , the first button (btnAdicionar) works fine, but when i press the button "btnRemover", i get an erron on the line "cmd.ExecuteNonQuery();"
what am i doing wrong? thanks
here is the code:
private void btnAdicionar_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "INSERT INTO Nomes (Nome, Sobrenome) VALUES(?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
private void btnRemover_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "DELETE FROM Nomes (Nome, Sobrenome) WHERE (?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
Your delete statement is not valid SQL, hence the error when you call ExecuteNonQuery
It should be something like this:
DELETE FROM Nomes WHERE Nome= ? and Sobrenome = ?

Categories