NVarChar for MySQL in C# - c#

I use this INSERT to add new record to database. But it can not show the Vietnamese in correct form. (Ex: Kh?ch s?n instead of Khách sạn).
How can I add "N" to the query in this case.
if (general.TestEmail.IsEmail(txt_Email.Text) == true)
{
//Insert dữ liệu vào database
email = txt_Email.Text;
MySqlCommand them_hotel = new MySqlCommand("INSERT INTO quan_li.hotel (name, star, address, province, phone, fax, email) VALUES (#name, #star, #address, #province, #phone, #fax, #email)");
them_hotel.CommandType = CommandType.Text;
them_hotel.Connection = conn_class.connection;
// them_hotel.Parameters.AddWithValue("#hid", txt_Hid.Text);
them_hotel.Parameters.AddWithValue("#name", txt_Ten.Text);
them_hotel.Parameters.AddWithValue("#star", txt_Sao.Text);
them_hotel.Parameters.AddWithValue("#address", txt_DiaChi.Text);
them_hotel.Parameters.AddWithValue("#province", txt_Tinh.Text);
them_hotel.Parameters.AddWithValue("#phone", txt_DienThoai.Text);
them_hotel.Parameters.AddWithValue("#fax", txt_Fax.Text);
them_hotel.Parameters.AddWithValue("#email", txt_Email.Text);
conn_class.OpenConnection();
them_hotel.ExecuteNonQuery();
conn_class.CloseConnection();
thanh_cong = "Đã thêm khách sạn thành công";
}
else
{
email_err = "Email không đúng định dạng \n";
}
Thank you very much for you help !
Solved:
I add Charset=utf8 to my connection string.
This is mine
public void Initialize()
{
server = "localhost";
database = "quan_li";
uid = "root";
password = "";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";" + "Charset=utf8";
connection = new MySqlConnection(connectionString);
}

Related

C# MySQL Error: Keyword not supported

I have a problem with my writting to database and reading from database.
Here is my code:
MySqlConnection conn = new MySqlConnection(ConnectionString);
string ID = "";
MySqlCommand cmdRegister = new MySqlCommand("Insert into Players (username,password) values('"+"John"+"', '"+"johnisbest"+"')", conn);
cmdRegister.ExecuteNonQuery();
MySqlCommand cmdRead = new MySqlCommand("SELECT ID FROM Players WHERE username = '"+this.username+"';", conn);
MySqlDataReader reader = cmdRead.ExecuteReader();
conn.Open();
while (reader.Read())
{
ID = (string)reader["ID"];
}
conn.Dispose();
return ID;
It give me always error: Keyword not supported
Thanks for every help ;)
EDIT:
public MySQL(string IPaddress, string port, string username, string password, string database)
{
ConnectionString = "datasource=" + IPaddress + ";port=" + port + ";username=" + username + ";password=" + password + ";database=" + database + ";charse=utf_8";
}
sql = new MySQL("IP address to database", "3306", "username to database", "Here is my password to database", "name of my database");
ConnectionString = "datasource=" + IPaddress + ";port=" + port + ";username=" + username + ";pwd=" + password + ";database=" + database + ";charse=utf_8";
Tried to replace password with "pwd";
for me this work fine
Server=localhost;Database=testing;UID=root;password=testing;connect timeout=700;charset=utf8;pooling=true;Port=3306

c# SQL Error - Must declare scalar

I have declared the scalar already but I am still getting the error. My code checks to see if an entry exists, if it does it updates the entry or if it does not exist it creates a new entry:
try
{
string server = Properties.Settings.Default.SQLServer;
string connection = "Data Source=" + server + ";Initial Catalog=Propsys;Persist Security Info=True;User ID=sa;Password=0925greg";
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open();
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #" + this.contactPersonTextBox.Text, cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
SqlDataReader myReader;
myReader = cmdCount.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count > 0)
{
string query = "UPDATE _1Agent SET DealID = #DealID, \n" +
"ContactPerson = #ContactPerson, \n" +
"Address = #Address, \n" +
"TaxVatNo = #TaxVatNo, \n" +
"Comm = #Comm, \n" +
"WorkTel = #WorkTel, \n" +
"Cell = #Cell, \n" +
"Fax = #Fax, \n" +
"Email = #Email, \n" +
"Web = #Web, \n" +
"CreateDate = #CreateDate, \n" +
"Notes = #Notes WHERE id = #id";
SqlCommand cm = new SqlCommand(query);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
else
{
string query1 = "INSERT INTO _1Agent (DealID, \n" +
"ContactPerson, \n" +
"Address, \n" +
"TaxVatNo, \n" +
"Comm, \n" +
"WorkTel, \n" +
"Cell, \n" +
"Fax, \n" +
"Email, \n" +
"CreateDate, \n" +
"Notes) VALUES ('" + txtDealNo.Text + "',\n" +
"'" + contactPersonTextBox.Text + "',\n" +
"'" + addressTextBox.Text + "',\n" +
"'" + taxVatNoTextBox.Text + "',\n" +
"'" + commTextBox.Text + "',\n" +
"'" + workTelTextBox.Text + "',\n" +
"'" + cellTextBox.Text + "',\n" +
"'" + faxTextBox.Text + "',\n" +
"'" + emailTextBox.Text + "',\n" +
"'" + notesTextBox.Text + "',\n" +
"'" + DateTime.Now + "')";
SqlCommand cm = new SqlCommand(query1);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query1;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Your usage of parameter is wrong, it should be:
SqlCommand cmdCount =
new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
Later you are adding the parameter correctly.
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
To get the count use SqlCommand.ExecuteScalar, instead of using DataReader:
int count = (int) cmdCount.ExecuteScalar();
For the other queries, UPDATE and INSERT, you can use a verbatim string, instead of concatenating strings over multiple lines.
string query = #"UPDATE _1Agent SET DealID = #DealID,
ContactPerson = #ContactPerson,
Address = #Address,
TaxVatNo = #TaxVatNo,
Comm = #Comm,
WorkTel = #WorkTel,
Cell = #Cell,
Fax = #Fax,
Email = #Email,
Web = #Web,
CreateDate = #CreateDate,
Notes = #Notes WHERE id = #id";
Other issues with the code:
You are concatenating strings to form INSERT query, later you are adding parameters, follow the same convention as UPDATE query and then use the parameters.
As pointed out in the other answer, you are not adding parameter#id value for UPDATE command
You are not specifying connection property with your UPDATE and INSERT command:
Specify it like
SqlCommand cm = new SqlCommand(query, cn);
Consider enclosing Connection and Command object in using
statement as it will ensure the proper disposal of unmanaged resources.
I see a few things;
Don't use string concatenation with # sign for parameters. That's wrong usage. Use it like;
"SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson"
and
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
and use ExecuteScalar to get first column of the first row. Using a reader is unnecessary for this command.
Your UPDATE query requires #id value since you declare it in your command as;
cm.Parameters.AddWithValue("#id", yourIDvalue);
Your INSERT query, you never declare your parameters in your command. You just concatenate them with their values. And use verbatim string literal to generate multiline strings instead of using \n.
Please
Read more carefully about parameterized queries and how you can use them.
Give me parameterized SQL, or give me death
You forget to mention parameter name in your select query
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
There are some wrong things .So you can refer #Soner Gönül and #habib answers
And change your insert query.Since you have declared paramertes but you didn't define.So change as follows
string query1 = "INSERT INTO _1Agent (DealID,ContactPerson,Address,TaxVatNo,
Comm, WorkTel, Cell, Fax, Email,Notes,CreateDate)
VALUES ( #DealID , #ContactPerson,#Address ,#TaxVatNo ,
#Comm,#WorkTel , #Cell,#Fax,#Email,#Notes,#CreateDate)";

sql missing comma

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ("+ ID + "," + password + "," + name + "," + position + "," + accessRight + "," + status + "," + createOn + "," +loginID+ ")";
readdata.updateData(sqlcommand);
}
I am passing the sqlcommand to readdata class for execute..and its throw me this error..
ORA-00917: missing comma
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: ORA-00917:
missing comma.
The readdata class function code as below.
public void updateData(string SqlCommand)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
OleDbCommand cmd = new OleDbCommand(SqlCommand, conn);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
}
Given that most of your columns are variable-length character, they must be enclosed in single quotes.
So, instead of:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES (" + InputValue + ")";
You would, at minimum, need this:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES ('" + InputValue + "')";
The result of the first statement, for an InputValue of "foo", would be:
INSERT INTO myTable (ColumnName) VALUES (foo)
which would result in a syntax error.
The second statement would be formatted correctly, as:
INSERT INTO myTable (ColumnName) VALUES ('foo')
Additionally, this code seems to be using values entered directly by the user, into txtID, txtPassword, and so on. This is a SQL Injection attack vector. Your input needs to be escaped. Ideally, you should use parameterized queries here.
This appears to be c#. Please update your tags accordingly.
At any rate, if it is .Net, here is some more information about parameterizing your queries:
OleDbCommand.Parameters Property
OleDbParameter Class
Try this
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ('"+ ID + "','" + password + "','" + name + "','" + position + "','" + accessRight + "','" + status + "','" + createOn + "','" +loginID+ "')";
Concatenating the query and executing it is not reccomended as it may cause strong SQl Injection. Suppose if any one of those parameters contain a comma(,) like USERPWD=passwo',rd then query will devide it as passwo and rd by the comma. This may be a problem
It is recommended that you use "Parameterized queries to prevent SQL Injection Attacks in SQL Server" and hope it will resolve your issue.
Your code can be rewritten as follows
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string strQuery;
OleDbCommand cmd;
strQuery = "INSERT INTO USERMASTER(USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES(#ID,#password,#name,#position,#accessRight,#status,#createOn,#loginID)";
cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#accessRight", accessRight);
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#createOn", createOn);
cmd.Parameters.AddWithValue("#loginID", loginID);
bool isInserted = readdata.updateData(cmd);
}
rewrite your updateData data as follows
private Boolean updateData(OleDbCommand cmd)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

How to update Datagridview after inserting Data

I can insert my data into MySql database, but on C# application I also want that the datagridview updates after pressing the button but I don't know how. It only refreshes in the datagridview after closing the C# application and opening again.
private void btnEintrag_Click(object sender, EventArgs e)
{
// Netzwerk IP-Adresse ermitteln
IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());
string IPAddress = Host.AddressList[1].ToString();
string datasource = IPAddress;
string database = "datenbank";
string port = "xxx";
string UID = "xxxx";
string pw = "xxx";
string myConnection;
myConnection = string.Format("datasource=" + datasource + ";" + "Database=" + database + ";" + "port=" + port + ";" + "UID=" + UID + ";" + "password=" + pw);
string VName, NName, Zusatztext;
VName = txtVName.Text;
NName = txtNName.Text;
Zusatztext = txtZusatz.Text;
Eintrag.CreateEntry(myConnection, VName, NName, Zusatztext); //Creates an Entry in the Table
}
private void BindGrid() //with this function I can see the data in datagridview
{
IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());
string IPAddress = Host.AddressList[1].ToString();
MessageBox.Show(IPAddress);
string datasource = IPAddress;
string database = "datenbank";
string port = "3306";
string UID = "outside";
string pw = "mysql";
string myConnection;
myConnection = string.Format("datasource=" + datasource + ";" + "Database=" + database + ";" + "port=" + port + ";" + "UID=" + UID + ";" + "password=" + pw);
using (MySqlConnection con = new MySqlConnection(myConnection))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Formular", con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
private void UpdateDataGridView()
{
?????? I don't know
}

How to save combobox items in database using the insert into query?

I want to save account in login database using combobox.
When I try to save, I'm presented with the error: "Syntax error in INSERT INTO statement". I tried to find the error in my INSERT INTO statement but i was unable to figure out whats wrong. This is the code I used to add items in combobox:
cmbAccountType2.DropDownStyle = ComboBoxStyle.DropDownList;
string str = null;
str = "User";
cmbAccountType2.Items.Add(str);
str = "Administrator";
cmbAccountType2.Items.Add(str);
And this is the query I used to saved the account in my login database:
private void btnSaveAccount_Click_1(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save item?", "Confirmation", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";
doSomething(q);
}
else if (result == DialogResult.No)
{
MessageBox.Show("Transaction cancelled.", "Information");
textClear();
}
loadData();
}
You have one extra comma here
"INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "'**, ,** '" + cmbAccountType2.Text.ToString() + "')";
that is the reason of error,but there are some other things you can make better in your code,
using (var cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(#name,#pw,#accType)",yourConnection))
{
cmd.Parameters.AddWithValue("name", txtUserName1.Text);
cmd.Parameters.AddWithValue("pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("accType", cmbAccountType2.Text);
cmd.ExecuteNonQuery();
}
Use parametirized query
Don't use redundant ToString() methods
cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(#name,#pw,#accType)",yourConnection)
cmd.Parameters.AddWithValue("#name", txtUserName1.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("#accType", cmbAccountType2.SelectedItem);
cmd.ExecuteNonQuery();
txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() +
I'm not absolutely sure, but since it's a syntax error, I'm assuming this is your error.
It's part of the line where you make the query string.
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";

Categories