What am I doing wrong with this C# .NET WinForms application? - c#

I am trying to edit an Access DB_. For some reason I cannot insert anything. I believe my code is correct. The connection string is correct (though for security purposes I put a fake one for this post). At the end, I do not get the MessageBox like I am supposed to at the end of the function. Nothing was added to the Access DB either.
Any reason why this might be?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}

Suggestion - please consider refactoring your code as follows, and step through it, a line at a time, in the MSVS debugger:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
If you wanted to use prepared statements, you'd change your code to something like this:
string sql = "insert into table1 values(#param1, #param2)";
...
cmd.Parameters.AddWithValue("#param1", textBox1.Text);
cmd.Parameters.AddWithValue("#param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
You can read more about techniques and guidelines for mitigating SQL injection here:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Here is another good article:
Best Practices for Using ADO.NET (MSDN)

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'values'.'

namespace login_page
{
public partial class itemselect : Form
{
public itemselect()
{
InitializeComponent();
}
private void product_Click(object sender, EventArgs e)
{
}
private void Addproduct_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-QI8RJIB;Initial Catalog=itemselect;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(" insert into itemselect([Product ID],[Product Name],[Product Quantity],[Product Price] values ('" +pid.Text+ "','" +pn.Text+ "','" +pq.Text+ "','" +pp.Text+ "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
this.Close();
MessageBox.Show("item added successfully");
}
Exception:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword
'values'.'
Your syntax is incorrect, make sure that you have closed all your opened parenthesis.
Also, always use SqlParameters to prevent Sql injection attacks and improve code readability
Sample code
private void Addproduct_Click(object sender, EventArgs e)
{
string query = "INSERT INTO itemselect ([Product ID],[Product Name],[Product Quantity],[Product Price]) VALUES (#ProductID, #ProductName, #ProductQuantity, #ProductPrice)";
using (var con = new SqlConnection(#"Data Source=DESKTOP-QI8RJIB;Initial Catalog=itemselect;Integrated Security=True"))
using (var cmd = new SqlCommand(query, con))
{
// Not sure about ProductID type. Could be SqlDbType.UniqueIdentifier or SqlDbType.Int / BigInt
cmd.Parameters.Add(new SqlParameter("#ProductID", SqlDbType.UniqueIdentifier)).Value = pid.Text;
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.NVarChar)).Value = pp.Text;
cmd.Parameters.Add(new SqlParameter("#ProductQuantity", SqlDbType.Int)).Value = pq.Text;
cmd.Parameters.Add(new SqlParameter("#ProductPrice", SqlDbType.Decimal)).Value = pp.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
// Records Inserted Successfully
}
catch (SqlException err)
{
// Error occured. Handle error
}
}
}
P.S: Please follow naming conventions when naming tables, columns and variables
You're missing a closing parathensis before the word values.
Also you should use a using statement to ensure that the connection
will be closed after the execution
You should also use a Parameters.AddWithValue() method to avoid the
SQL INJECTION

C# sql related exception [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to do a simple C# windows application as a beginner. But I get a System.Data.SqlClient.SqlException. When I try to connect to database it says connection is OK. But it doesn't allow me to create any tables using visual studio. I can't figure out why it doesn't show options to add new table.
Here is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace best
{
public partial class Form1 : Form
{
SqlConnection con=new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Janith Kularathne\Documents\testing.mdf;
Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void insertB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into details values('"+ idBox.Text +"', '"+ nameBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text="";
DisplayDetails();
MessageBox.Show("Insertion succesfull");
}
private void deleteB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from details where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text = "";
DisplayDetails();
MessageBox.Show("delete succesfull");
}
private void updateB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update details set id, name,category where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text = "";
DisplayDetails();
MessageBox.Show("Update succesfull");
}
private void searchB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "selet *from details where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
DisplayDetails();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
DisplayDetails();
}
public void DisplayDetails()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from details";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
}
Your code currently contains a variety of different issues, which I'll elaborate a bit on and should resolve some of your current problems :
Unnecessary closing parentheses
Typos and Misspellings
Incorrect Syntax
Using Parameterization
In addition to these, I'd highly recommend reading through some tutorials on using the different methods like ExecuteNonQuery(), ExecuteReader() and ExecuteNonScalar() to determine how to actual retrieve values from your queries once you execute them.
Unnecessary Closing Parentheses
You currently have a trailing closing parentheses within each of your queries which is likely causing a syntax error within your SELECT, UPDATE, and DELETE queries :
// Notice the unnecessary trailing ')', which should only be useful within your INSERT call
cmd.CommandText = "..." + idBox.Text + "')";
Typos and Misspellings
An additional typo is present within your search query as well as the word "SELECT" is misspelled:
// "selet" should be "Select"
cmd.CommandText = "selet *from details where id= '" + idBox.Text + "')";
Incorrect Syntax
Your current UPDATE query doesn't actually appear to be doing anything. You are using the SET keyword, but aren't actually setting the values to anything :
// UPDATE queries should be in the form UPDATE {table} SET {Column} = {Value} WHERE ...
cmd.CommandText = "update details set id, name,category where id= '" + idBox.Text + "')";
Parameterization, Not Concatenation
Additionally, you should really consider using parameterization when building your queries. It can help avoid nastiness like SQL Injection and prevent syntax errors as well.
You can see an example of what this might look like for one of your methods below :
private void searchB_Click(object sender, EventArgs e)
{
con.Open();
var query = "SELECT * FROM details WHERE ID = #id";
using(var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#id",idBox.Text);
using(var reader = cmd.ExecuteReader())
{
// Access your results here and do something with them
}
}
}

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.

How to insert into a Service-based Database

public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dimmer\Documents\Visual Studio 2013\Projects\Manage components\Manage components\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadlist();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "insert into info (id,name) values ('"+txtid.Text+"'.'"+txtname.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record instered!");
txtid.Text = "";
txtname.Text = "";
loadlist();
}
}
}
I am new to C# and I have been trying for some hours with a insert code to a service-based database. I have tested the connection to it and it works.
I got this error message:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'xxxx'.
Where xxxx is what I insert into my 2nd textbox. The code stops at
cmd.ExcecuteNonQuery();
I have been searching for an answers for hours, I believe there is something wrong with the database.
Sorry if this code looks ugly, but I had some problems with spaces :P
You didn't tell us what are txtid.Text and txtname.Text exactly but..
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
cmd.CommandText = "insert into info (id,name) values (#id, #name)";
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.ExecuteNonQuery();
Looks like you're reusing a connection and you probably have not closed it last time.
You should always close a connection immediately as soon as you're finished with it. Use using statement like;
using(var cn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(query, cn))
{
if (txtid.Text != "" & txtname.Text != "")
{
cmd.CommandText = "insert into info (id,name) values (#id, #name)";
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
...
}
}

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