MySql connection in C# - c#

i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:
public void Query_send(string cmd)
{
String config = "server=127.0.0.1;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = config;
conn.Open();
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
and then in the BUTTON to give the informations for the MySql i use this:
private void button1_Click(object sender, EventArgs e)
{
Query instance = new Query();
instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
}
i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this?
Thanks, Iago.

My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.
VALUES ('" + textbox1 + "')
Brackets are only required when referring to table or column names. Not when you're referring to string literals.

Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.
Not sure if that will help, but it's process of elimination.
Also not sure if method was work in process, but even if it connected there was no execute command against the database.
public void Query_send(string cmd)
{
String config = "server=localhost;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn.Open();
comm.ExecuteNonQuery(); '--this was missing
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}

Related

OleDbCommand is not persisted in the DB

I'm learning C# for a small project with an Access DB.
I get no error when I click on the button to run my sql statement through OleDbCommand but no row is inserted in the table though.
I think my connection is perfectly set up because I get an error if I don't use the right type for a column (e.g. insert a string in an int).
I know the button is working too because I add an action on a text which is working. Finally I know also that my query works since I have tried it directly via VS on my table.
Am I missing a step?
Here my code:
namespace ProjetFalk
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btn_onclick_Click_1(object sender, EventArgs e)
{
label12.Text = string.Empty;
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=DBFalk.accdb";
OleDbConnection dbconn = new OleDbConnection(connectionString);
dbconn.Open();
string dbcommand = "INSERT INTO Produit (NOM,REFERENCE) VALUES('TEST2', 'test2')"; // + TextBox_Nom.Text + "')";
OleDbCommand cmd = new OleDbCommand(dbcommand, dbconn);
cmd.ExecuteNonQuery();
dbconn.Close();
}
}
}
Please be tolerant, it's new for me. (I have read the docs on Microsoft too for my setup)

SQL Update statement on Winforms

I'm still learning C#, I wanna ask about Update statement, I got a problem when updating data ... the process is success but data on database doesn't updated.. Did i do some mistake on this?
MySqlConnection con = new MySqlConnection("server=127.0.0.1;database=cproject;Uid=root;Pwd=admin");
MySqlDataAdapter oDA;
DataTable oDT = new DataTable();
MySqlCommand job;
private void button1_Click(object sender, EventArgs e)
{
job = new MySqlCommand("UPDATE barang SET Nama_barang = '"+txtNama+"' AND Jumlah_barang='"+txtStock+"' AND Harga_awal='"+txtBeli+"' AND Harga_jual='"+txtJual+"' WHERE ID = '"+txtIndex+"'", con);
try
{
con.Open();
job.ExecuteNonQuery();
MessageBox.Show("sukses");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
did I do something wrong?
Few Instructions: You are trying the wrong syntax here for SQL UPDATE, IF you have to update more columns then each one should be separated with commas, not with AND, One more thing you have to take care of is that your code opens a wide door for hackers through injection, To close this door you have to use parameterized queries. Another thing( but not sure), The names txtNama, txtStock etc looks like the names of TextBoxes if so you have to use its .Text properties as well. if not use proper naming conventions.
In simple your code should be like the following:
MySqlCommand sqlCommand = new MySqlCommand("UPDATE barang SET Nama_barang =#Nama_barang,Jumlah_barang=#Jumlah_barang,Harga_awal=#Harga_awal,Harga_jual=#Harga_jual WHERE ID =#id", con);
sqlCommand.Parameters.AddWithValue("#Nama_barang", txtNama.Text);
sqlCommand.Parameters.AddWithValue("#Jumlah_barang", txtStock.Text);
sqlCommand.Parameters.AddWithValue("#Harga_awal", txtBeli.Text);
sqlCommand.Parameters.AddWithValue("#Harga_jual", txtJual.Text);
sqlCommand.Parameters.AddWithValue("#id", txtIndex.Text);
try
{
con.Open();
sqlCommand.ExecuteNonQuery();
MessageBox.Show("sukses");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
You can try .Parameters.Add() if the values are of different types,
I believe you have the values coming in from TextBox as the Naming shows txtNama, txtStock So it should be txtNama.Text, txtStock.Text respectively. Another one which I believe it should be is that the Table in the DB would not be all Varchar Field. For Varchar field we need 'Value' but for int or numbers we should not be using 'value' whereas it should be value. So your Query should look like
"UPDATE barang SET Nama_barang = '" + txtNama.Text + "', Jumlah_barang=" + txtStock.Text + ", Harga_awal=" + txtBeli.Text + ", Harga_jual='" + txtJual.Text + "' WHERE ID = " + txtIndex.Text
I am not sure which of the fields are numeric. So I just removed '' for few which I think would be numeric. Now you should use Using Statement and Parameterized Query to care the SQL Injection. and thus your code would look like
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE barang SET Nama_barang = #namabarang, Jumlah_barang = #Jumlahbarang, Harga_awal= #Hargaawal, Harga_jual=#Hargajual WHERE ID = #myID";
command.Parameters.AddWithValue("#namabarang", txtNama.Text);
command.Parameters.AddWithValue("#Jumlahbarang", txtStock.Text);
command.Parameters.AddWithValue("#Hargaawal", txtNama.Text);
command.Parameters.AddWithValue("#Hargajual", txtBeli.Text);
command.Parameters.AddWithValue("#myID", txtJual.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

How to get alert when Unique key is violated

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=VIVID-PC;Integrated Security = True;Database=SchoolDb");
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
myConnection.Open();
string firstText = TextBox1.Text;
string SecondText = TextBox2.Text;
string thirdText = TextBox3.Text;
string fourthText = TextBox4.Text;
myCommand = new SqlCommand("INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)values('" + firstText + "','" + SecondText + "' , '" + thirdText + "','" + fourthText + "')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
Use command with parameters to pass data to server.
Make sure you dispose connection and command (via using statement)
Store connection strings in config file
Do not create dummy command objects
Here is complete code:
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText =
#"INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)
VALUES (#studentName, #rollNo, #session, #mobileNo)";
command.Parameters.AddWithValue("studentName", TextBox1.Text);
command.Parameters.AddWithValue("rollNo", TextBox2.Text);
command.Parameters.AddWithValue("session", TextBox3.Text);
command.Parameters.AddWithValue("mobileNo", TextBox4.Text);
connection.Open();
try
{
command.ExecuteNonQuery();
}
catch(SqlException e)
{
if (e.Message.Contains("Violation of UNIQUE KEY constraint"))
// you got unique key violation
}
}
Further considerations - improve naming in your code - TextBox1, TextBox2 etc says nothing to reader. Give them appropriate names, like StudentNameTextBox, RollNoTextBox etc. Also good practice is splitting data access and UI logic.
If the database detects a unique key violation, this line
myCommand.ExecuteNonQuery();
will throw an exception. You can catch that exception and proceed with your own code:
try
{
myCommand.ExecuteNonQuery();
}
catch(Exception e)
{
// right here, "something" went wrong. Examine e to check what it was.
}
Please note that your code is vulnerable to SQL injection attacks. You should be using command paramaters instead of building the SQL manually. In addition, you should be using using blocks (see here for details)
ExecuteNonQuery will throw an exception if it's unable to INSERT row into database. In your case, it's most likely an SqlException. Catch it.
use your returnType from ExecuteNonQuery() (Read the remarks part) to detect failure in insertion. you can use the exception or the no. of rows affected part
Try this :
try
{
... your rest of the code
...
int rowsAffected = myCommand.ExecuteNonQuery(); // Most probaboly it will throw exception in case of Unique key violation. If not, still no rows have been affected
if(rowsAffected<1)
{
//your Alert for no records inserted
}
else
{
//your alert for successful insertion
}
}
catch(SqlException ex)
{
//check the exception and display alert
}
finally
{
//release connection and dispose command object
}
As suggested in comment use command param.
try
{
//Your other code
_myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
catch(SqlException sqlExc)
{
// Your popup or msg.
}
You also loop for different sql error in catch block.

Record inserted successfully but database not updated C# and SQL Server Compact Database

private void button1_Click(object sender, EventArgs e)
{
string usernames = textBox1.Text;
string passwords = textBox2.Text;
string emailid = textBox5.Text;
string telno = textBox6.Text;
string connectionstring = "Data Source=|DataDirectory|\\libdb.sdf; Persist Security Info=False ;";
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
con.Open();
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
Query.ExecuteNonQuery();
}
MessageBox.Show("QueryExecuted");
con.Close();
MessageBox.Show("Closedconnecrion");
con.Dispose();
MessageBox.Show("disposed");
this.Close();
/*string conString = "Data Source=" +
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyAppData\\database.sdf") + ";Password=yourPassword;";
even this method dosent works */
}
}
}
on executing this code I find it executes successfully. But when I go and check the database, I find the entries empty...
I even tried refreshing database..
I didn't find problem in connectivity.
Query no error executed successfully.
The problem is I didn't find result or the data I gave as input in database.
Please be descriptive with code eg and mail to scarlet.gabriel#gmail.com
Test your connection with the database first, You can get the connection string by creating the udl file.
create a textfile and savaas it with the extension udl (example connection.udl).
double click and run this file.
a window will be opened where you can get the option for getting the connection string.
after testing the connection, close this window and open this file with a note pad.
copy the connection string and paste it in the below statement.
string connectionstring =" paste here";
How can you be sure if the connection is open and has done the job? Use try... catch block to catch if any error occurs:
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
try{con.Open();}
catch(Exception ex)
{
// database connection error. log/display ex. > return.
}
if(con.State==ConnectionState.Open)
{
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
try{
Query.ExecuteNonQuery();
}
catch(Exception ex)
{
// database communication error. log/display ex
}
}
MessageBox.Show("QueryExecuted");
}
if(con.State==ConnectionState.Open)
{
try{con.Close();}
catch{}
}
}
Instead of using connectionstring = "Data Source=|DataDirectory|\libdb.sdf; Persist Security Info=False ;"; Please try to use absolute path like
connectionstring = "Data Source=C:\Users\chandra\Documents\Visual Studio 2010\Projects\Window\LMS\AppData\LMSDatabase.sdf;Persist Security Info=False;";
I hope this will work.
Thanks

Null Reference Exception in database handling

in c sharp in win forms i am encountering an error, something like null reference exception
this is my code...and also I don't find any entries in the database table...
public partial class Form1 : Form
{
string strCon, strQry;
SqlConnection con;
SqlCommand cmd;
int rowsaffected;
public Form1()
{
InitializeComponent();
}
box s2 = new box();
class box
{
protected string fname;
protected string lname;
public void name(string s1, string s2)
{
fname = s1;
lname = s2;
}
}
void func(string x, string y)
{
s2.name(x, y);
}
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
func(first, last);
strQry = "Insert Into Practice Values(" + first + "," + last + " )";
cmd = new SqlCommand(strQry, con);
cmd.Connection.Open();
rowsaffected = cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show(+rowsaffected + " row(s) affected");
}
private void Form1_Load(object sender, EventArgs e)
{
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
con = new SqlConnection(strCon);
}
alt text http://img682.imageshack.us/img682/6017/hjki.jpg
sorry i didnt mention initialize it u mean to say con = new SqlConnection(strCon); i have done dat in dat case error is {"The name 'xyz' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted."}
You are not instantiating the con variable, for example:
SqlConnection con = new SqlConnection(connectionString);
I suppose the error happens because you use con, that is not initialized.
I don't see a SqlConnection con = new SqlConnection(strCon);
I bet your problem is with the connection string, and the connection object is null. Here is a quick way to generate and test a connection string:
Right click the windows desktop or inside a folder in windows explorer,
Click New -> Text Document
Rename the new file to Test.udl (.udl stands for Universal Data Link)
Create and test your connection with the UDL Dialog and click OK
Rename Test.udl to Test.txt and open the text file.
The text file will have a valid connection string that you can use in your code.
Also for your reference, I have simplified your code. The following should be much easier to debug:
private const string dbConnection = "USE THE UDL STRING HERE";
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
//I think the orig code was missing the single quotes
string query = string.Format("INSERT INTO Practice ('{0}','{1}')", first, last);
int rowsAffected = 0;
//Using statement will automatically close the connection for you
//Using a const for connection string ensures .NET Connection Pooling
using (SqlConnection conn = new SqlConnection(dbConnection))
{
//Creates a command associated with the SqlConnection
SqlCommand cmd = conn.CreateCommand();
//Set your sql statement
cmd.CommandText = query;
//open the connection
cmd.Connection.Open();
//Execute the connection
rowsAffected = cmd.ExecuteNonQuery();
}
MessageBox.Show(rowsAffected + " rows Affected");
}
Are you setting a connection string? It appears you are accessing the Connection object without telling it where to insert the data.
cmd.Connection.ConnectionString = "some string";
I don't think you need cmd.Connection.Open and cmd.Connection.Close.
cmd will open the connection & close it, in order to execute the query/stored procedure.
You are actually creating you connection correctly. What is happening is if you look at your connection string
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
when it tries to connect it reads this as:
Data Source: " (local)"
Initial Catalog: " Student"
User Id= " sa"
Password - "sa"
So the spaces that you have after the equals signs are getting passed to the SQL server. What your string should look like is this
strCon = "Data Source =(local); Initial Catalog=Student;User Id=sa;Password=sa;"
I am pretty sure that you are never getting an actual connection to your database, but it's failing silently.
Any time you get a null reference on a line that has multiple calls linked together like:
something.somethingElse.somethingElse
break it apart and check each piece. For example, in your case this code:
cmd = new SqlCommand(strQry, con);
SqlConnection sc = cmd.Connection;
System.Diagnostics.Debug.Assert(sc != null, "You got a null connection from the SqlCommand.");
sc.Open();
may demonstrate what the problem is.

Categories

Resources