Insert Data Into Databse Once User Clicks on Button - c#

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.

Related

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

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)

Error with Sql Parameters

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();
}

object reference not set to an instance of an object, sql query not runnable?

I'm pretty sure that the Sql Syntax is right since it's a legit query.
However i've never stumbled on this issue before.
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
{ MessageBox.Show(ex.Message); }
}
}
The problem may be related to this:
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
cmd.ExecuteNonQuery
MessageBox.Show("Användaren borttagen.");
}
Now you've shown us your whole code in the comments, the problem is obvious.
You have written a method to initialise, set up and open your database connection; and this other method which runs on a button click, which uses it.
However, nowhere in your code do you call the method which initialises your database connection, therefore it is not set up when you try to use it - obvious really.
I can see you think you are checking to see if the connection is working by checking its State property, but calling any sort of method or property accessor on an uninitialised reference type won't work, you'll get the NullReferenceException you've been getting.
To fix, call the connection set up method from your button press, before trying to use the connection:
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
db_connection(); //added this line
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have not defined the variable, "connect".

Insert data into local database using ado.net in a console application

Here is what I have written so far.There is no exception so I am assuming the connection is working fine but no data is inserted into the database table. Please tell me what is wrong with my code
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString);
try
{
conn.Open();
// foreach (student stu in stulist)
// {
string strQuery = "INSERT INTO Student(Sid,st_name) VALUES (#id,#name)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#id", "111");
cmd.Parameters.AddWithValue("#name", "nallia");
cmd.ExecuteNonQuery();
}
catch
{
conn.Close();
}
Try this
static void Insert()
{
try
{
string connectionString =System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString;
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Student(Sid,st_name) VALUES (" +
"#id,#name)", conn))
{
cmd.Parameters.AddWithValue("#Id", 111);
cmd.Parameters.AddWithValue("#Name", "nallia");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
It has been nearly 2,5 years but if you haven't still solved this problem, you should change the "copy to output directory" attribute to "copy if newer". Your database is changing but every time you start debugging, you read the initial version of database so, you see that there is no changes.

C# Database issue

Could somebody tell me why this isn't adding the values to the database. The form runs fine and doesn't return any errors.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
command.CommandText = "INSERT INTO Setup (userName, password) VALUES(#userName, #passWord)";
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception
}
finally
{
connection.Close();
}
}
FYI: I'm a "newbie" My database is called Setup. I've manually added a table called myTable with 2 columns of userName and another one called password both set at nchar(50)
You need to specify the Table, not the database (which gets used in the connection string). Added the schema prefix to the table name:
command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (#userName, #passWord)";
And add:
command.Connection = connection;
to associate your Command object with the connection object.
Your code should look something like this:
Set the connection object.
Specify the table name as #LarsTech has mentioned.
It is a best practice to use two part notation when specifying table names like [Schema name].[Table Name]. So, you have to specify your table name like dbo.MyTable
Code snippet:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO dbo.MyTable (userName, password) VALUES (#userName, #passWord)";
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
finally
{
connection.Close();
}
}
The form runs fine and doesn't return any errors.
That's probably because you're swallowing them. Get rid of (or log) your catch (Exception ex).
In general, the .NET BCL is well-designed - if a method isn't going to work, you will get an exception.
[Now] I have the error 'ExecuteNonQuery: Connection property has not been initialized.'
Right. You need to pass the SqlConnection to the SqlCommand:
SqlCommand command = new SqlCommand();
command.Connection = connection;

Categories