Error with Sql Parameters - c#

private void btnadd_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql = ("Insert into tbl_books values NameOfBook = #book, Author =#author, Publisher=#publisher,YearPublished=#year,Category=#category,ISBN=#isbn");
MySqlCommand sda = new MySqlCommand(sql,conn);
sda.Parameters.AddWithValue("#book", txtbook.Text);
sda.Parameters.AddWithValue("#author", txtauthor.Text);
sda.Parameters.AddWithValue("#publisher", txtpublisher.Text);
sda.Parameters.AddWithValue("#year", txtyear.Text);
sda.Parameters.AddWithValue("#category", cmbcategory.Text);
sda.Parameters.AddWithValue("#isbn", txtisbn.Text);
sda.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Item has been added");
showlv("Select * from tbl_books", lvbooks);
}
catch (Exception)
{
MessageBox.Show("Cannot Add Item");
}
}
What is wrong with the code? It keeps on going into the catch block.

Your SQL is messed up. Try:
try
{
conn.Open();
string sql = "Insert into tbl_books (NameOfBook,Author,Publisher,YearPublished,Category,ISBN) values (#book,#author,#publisher,#year,#category,#isbn)";
MySqlCommand sda = new MySqlCommand(sql,conn);
sda.Parameters.AddWithValue("#book", txtbook.Text);
sda.Parameters.AddWithValue("#author", txtauthor.Text);
sda.Parameters.AddWithValue("#publisher", txtpublisher.Text);
sda.Parameters.AddWithValue("#year", txtyear.Text);
sda.Parameters.AddWithValue("#category", cmbcategory.Text);
sda.Parameters.AddWithValue("#isbn", txtisbn.Text);
sda.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Item has been added");
showlv("Select * from tbl_books", lvbooks);
}
And THANK YOU for taking the time to learn about parameterization. In-line SQL is the ripest tool for hackers and the most embarrassing and easy-to-fix security hole there is!
NOTE: you may want to bring your conn into the TRY block and wrap it in a USING statement to save resources:
using(SqlConnection conn = getMyConnection())
{
conn.Open();
//blah
conn.Close();
}

Related

INSERT SQL statement with button click event issue

I feel like I'm missing something minor. This btnSave_Click event handler should update my database - what am I missing? I'm not getting any error message.
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
string mainconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand();
String sqlquery = "INSERT INTO dbo.TestTable (EDIPI) VALUES(#EDIPI)";
sqlcomm.CommandText = sqlquery;
sqlcomm.Connection = sqlconn;
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 5).Value = txtEDIPI.Text;
sqlconn.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error is " + exp.ToString());
}
}
You need to add:
sqlcomm.ExecuteNonQuery()
I just need to add sqlcomm.ExecuteNonQuery(); Thank you everyone! and user2042214 for the answer just with a extra period.

Insert Data Into Databse Once User Clicks on Button

I am trying to write a code that will insert data into a database once user click on button. There's something wrong with the code and it does not seem to work properly. I connect to an external database based on my hosting provider.
private void druk_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=s59.hekko.net.pl;uid=truex2_kuba;" +
"pwd=test;database=truex2_kuba;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd.CommandText = "insert into [barcode]values(#class, #tree, #type, #amount, #length, #width, #square)";
cmd.Parameters.AddWithValue("#class", klasa.Text);
cmd.Parameters.AddWithValue("#tree", gatunek.Text);
cmd.Parameters.AddWithValue("#type", rodzaj.Text);
cmd.Parameters.AddWithValue("#amount", amount.Text);
cmd.Parameters.AddWithValue("#length", length.Text);
cmd.Parameters.AddWithValue("#width", width.Text);
cmd.Parameters.AddWithValue("#square", textBox1.Text);
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Zapisane do raportu");
}
The issue is this:
MySqlCommand cmd = new MySqlCommand();
is in the scope of the try, catch block.
Further on in the code, there was a reference to the cmd variable which is null and hence no data goes in.
Move it outside of the try, catch block.

Works perfectly except changes are not saved to the SQL database

Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);

SQL Insert Query Using C#

I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}

C# Inserting Data from a form into an access Database

I started learning about C# and have become stuck with inserting information from textboxes into an Access database when a click button is used.
The problem I get is during the adding process. The code executes the Try... Catch part and then returns an error saying "Microsoft Access Database Engine" and doesn't give any clues.
Here is the code:
namespace WindowsFormsApplication1
{
public partial class FormNewUser : Form
{
public FormNewUser()
{
InitializeComponent();
}
private void BTNSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Copy Cegees\Cegees\Cegees\Login.accdb";
String Username = TEXTNewUser.Text;
String Password = TEXTNewPass.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Login (Username, Password) Values(#Username, #Password)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = Password;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
Password is a reserved word. Bracket that field name to avoid confusing the db engine.
INSERT into Login (Username, [Password])
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
and doesnt give any clues
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
Don't ignore the exception, it contains information about what went wrong and why.
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.
In your debugger, place a breakpoint inside the catch block and examine the details of the exception. You'll find it contains a lot of information.
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(# "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}

Categories