mysql parameter set null to database by c# - c#

I have an method like below in C# and i'm gonna to parameterize my query but name field get null value in database .testTable(id,name) and id is auto increament.mysql ver is 5.6
private void buttonTest_Click(object sender, EventArgs e)
{
string query = "insert into testdb.testTable(name) VALUES (#name) ;";
MySqlConnection conDataBase = new MySqlConnection(myfunctions.ConnString);
conDataBase.Open();
MySqlCommand cmd = new MySqlCommand(query, conDataBase);
try
{
cmd.Connection = conDataBase;
cmd.Parameters.AddWithValue("#name","John");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}

try this in place of varchar,50 enter your dbtype
string query = "insert into testdb.testTable(name) VALUES(_name) ;";
and
cmd.Connection = conDataBase;
cmd.Parameters.Add("_name", MySqlDbType.VarChar, 50).Value = "John";
cmd.ExecuteNonQuery();

Try like this
command.Parameters.Add("#name", SqlDbType.VarChar,50);
command.Parameters["#name"].Value = "john";

Related

C# update combobox with Database values

Hello I have a database with drivers and a combobox which is populated with the drivers. But when I add a new driver with a button Add Driver, it's added only in Microsoft Access table, not in the combobox. And once I reload the program, the new driver is deleted from the database. I also have connected the database in Data Source and I can edit the tables only from there(if I want to edit the combobox).
This is my connection with the database
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
cmd = new OleDbCommand();
con.Open();
cmd.Connection = con;
string query = "SELECT Name FROM Drivers";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboDriver.Items.Add(reader["Name"]);
}
con.Close();
and this is my Add Driver button:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
String Id = textID.Text;
String Name = textName.Text;
String Age = textAge.Text;
String City = textCity.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Drivers (Id, Name, Age, City) Values(#Id, #Name, #Age, #City)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Id", OleDbType.VarChar).Value = Id;
cmd.Parameters.Add("#Name", OleDbType.VarChar).Value = Name;
cmd.Parameters.Add("#Age", OleDbType.VarChar).Value = Age;
cmd.Parameters.Add("#City", OleDbType.VarChar).Value = City;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("New Driver Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
Just because you've added it to your database, doesn't mean anything else will happen.
You still need to update your UI.
Add this in after you have executed the query:
comboDriver.Items.Add(Name);
As an aside, you should also wrap the conn.Open() in a try catch as well

I have a listview with items which I want to insert into a SQL Server database

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.)

fatal error encountered during command execution in c#.net mysql

I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.

data-type-mismatch-in-criteria-expression-error when delete from MS Access with ADO.NET C#

i write code that insert and delete some data with Microsoft Access database , i can insert the data but when i delete it i have an error "data-type-mismatch-in-criteria-expression" i don't know why !!! Any one help me ?
thanks in advance ;
private void Savebt_Click(object sender, EventArgs e)
{
//try
//{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\me\Library Store\Library Store\Store.accdb");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Libarary ( ISBN, [Name], Gategory, Author, Cost, [Date]) " +
"VALUES ( #ISBN, #Name, #Gategory, #Author, #Cost, #Date) ";
cmd.Parameters.AddWithValue("#ISBN", ISBNTB.Text);
cmd.Parameters.AddWithValue("#Name", NameTB.Text);
cmd.Parameters.AddWithValue("#Gategory", GategoryTB.Text);
cmd.Parameters.AddWithValue("#Author", AuthorTB.Text);
cmd.Parameters.AddWithValue("#Cost", int.Parse(CostTB.Text));
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Book Added!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void sellbt_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\me\Library Store\Library Store\Store.accdb");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = " DELETE * FROM Libarary WHERE ISBN=#ISBN AND [Name]=#Name AND Gategory=#Gategory AND Author=#Author AND Cost=#Cost AND [Date]=#Date ";
cmd.Parameters.AddWithValue("#ISBN", ISBNTB.Text);
cmd.Parameters.AddWithValue("#Name", NameTB.Text);
cmd.Parameters.AddWithValue("#Gategory", GategoryTB.Text);
cmd.Parameters.AddWithValue("#Author", AuthorTB.Text);
cmd.Parameters.AddWithValue("#Cost", CostTB.Text);
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Book removed to be sold!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Errow with the record which i try to delete
database records
You are facing this error because one/many parameters that you are passing to your query are of not the same type as it is in the database. Cross check them. and ideally should pass parameters to your query like this
cmd.Parameters.Add("#Date", OleDbType.Date); //note i have specified the db type
cmd.Parameters["#Date"].Value =dateTimePicker1.Value;
this will ensure that you have same types as defined in your database
Try:
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Value);
DateTimePicker.Text returns string representation of selected value, not the value itself.
How about?
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Value.ToString("dd-MM-yyyy"));

Stored Procedure ADO.NET error

Hello I have a Stored Proc for the Registration Page, but I need ADO.NET to take values from various textboxes.
However, I'm recieving error like this:
"System.ArgumentException: No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type. "
public void InsertInfo()
{
String empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(empdb);
SqlCommand cmd = new SqlCommand("bridge_Type", conn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("#Name", TextBox2.Text));
cmd.Parameters.Add(new SqlParameter("#Mob2", TextBox3.Text));
cmd.Parameters.Add(new SqlParameter("#Email", TextBox14.Text));
cmd.Parameters.Add(new SqlParameter("#Emptype", dropdown1.SelectedValue));
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertInfo();
}
Then I used this format to add values from controls:
cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
cmd.Parameters("#EmpID").Value = TextBox1.Text;
I'm getting errors on:
Its showing errors for these kind of codes by appearing red line under 'Parameters'.
Non-invocable member 'System.Data.SqlClient.SqlCommand.Parameters' cannot be used like a method.
Try TextBox1.Text, TextBox is the Control. The Text property holds the String value.
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
Try this code.
try
{
string empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("bridge_Type",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpID",TextBox1.Text);
cmd.Parameters.AddWithValue("#Name", TextBox2.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox3.Text);
cmd.Parameters.AddWithValue("#Email", TextBox14.Text);
cmd.Parameters.AddWithValue("#EmpType",dropdown1.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
string msg = "Insert Error:"+ ex.Message;
throw new Exception(msg);
}
Make sure you are converting to the types same as the Parameter types in your stored proc ( Ex: If the parameter type of EmpID is int, you may need to convert the TextBox1.Text value to int. Check for null values also.
why dont u use this format?
cmd.Parameters.Add("#parameter", SqlDBType , size).value = TextBox1.Text

Categories

Resources