Storing Japanese characters from a form TextBox to SQL table appears as question marks.
I'm just trying to make a table that holds the Japanese text and the English translation to make my life easier as I'm studying Japanese.
Searching for a solution 2 days now nothing seems to be working.
I am not even sure if this is actually a good practice for storing text to data table.
Also column where I want the Japanese character stored is set to nvarchar(50).
private void addWordButton_Click(object sender, EventArgs e)
{
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT Words (WordJapanese, WordEnglish) VALUES ('" + newJPwordTxt.Text + "', '" +
newENwordTxt.Text + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
It seems you have missed the into keyword in your Insert statement, as a second note, you need to be aware that this kind of string concatenation is avoided and it is open to SQL Injection attack. You should always use parameterized queries to avoid SQL Injection:
cmd.CommandText = "INSERT into Words (WordJapanese, WordEnglish) VALUES (#WordJapanese, #WordEnglish)";
cmd.Parameters.Add("#WordJapanese", SqlDbType.NVarChar, 50).Value = newJPwordTxt.Text;
cmd.Parameters.Add("#WordEnglish", SqlDbType.NVarChar, 50).Value = newENwordTxt.Text;
Your query has syntax issues and secondly you should be using parameterized queries to safeguard from SQL Injection.
The following should be good :
cmd.CommandText = "INSERT INTO Words(WordJapanese, WordEnglish) VALUES (#Japanse, #English)";
cmd.Parameters.Add("#Japanse", SqlDbType.NVarChar, 50).Value = newJPwordTxt.Text;
cmd.Parameters.Add("#English", SqlDbType.NVarChar, 50).Value = newENwordTxt.Text;
Related
New to C#. Trying to insert values into a Microsoft Access Database using this code:
string value = "It's a nice day"
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values('"+ value + "')";
cmd.ExecuteNonQuery();
con.Close();
But I get the error 'Syntax error (missing operator) in query expression' which I'm going to assume, stems from the apostrophe in the string value. Is there any way around this?
Every time you need to pass values to execute an sql query you should ALWAYS use a parameterized query. As you have experienced, apostrophes mess with the syntax when you concatenate strings.
A parameterized query for your case should be
string value = "It's a nice day"
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values(#value)";
cmd.Parameters.Add("#value", OleDbType.VarWChar).Value = value;
cmd.ExecuteNonQuery();
This will remove the problem with apostrophes, interpretation of the decimal point symbol, date format, but, most important even is not easy to exploit with Access, the Sql Injection ack.
I have this INSERT statement,
"INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
$"VALUES ('{name}','{email}','{address}')";
So as you can see on the 2nd line, i have added '$'. This version of the code works, but it's not supported in VS2012.
I'm trying to convert this into something like this but I'm having a lot of issues since it's so very complicated .
"INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
"VALUES (''" + name + "', ''" + email + "', ''" + address + "')";
This version above doesn't work. Basically i'm trying to make a query without using the '$' Any ideas?
Don't do that at all, it exposes you to SQL injection attacks and converions issues. What would a date look like if you tried to pass it using string concatenation? A decimal?
It's actually easier to use parameterized queries :
//Create a SqlCommand that can be reused
SqlCommand _cmdInsert;
var sql="INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
"VALUES (#name,#email,#address)";
var cmd=new SqlCommand(cmd);
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 30);
cmd.Parameters.Add("#email", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#address", SqlDbType.NVarChar, 50);
_cmdInsert=cmd;
Later, you can use the command directly by setting a connection and parameter values :
using(var connection=new SqlConnection(theConnectionString)
{
_cmdInsert.Connection=connection;
_cmdInsert.Parameters["#name"].Value=someName;
...
connection.Open();
_cmdInsert.ExecuteNonQuery();
}
Parameterized queries pass the strongly-typed values alongside the query in the RPC call. A DateTime is passed as a DateTime (or the binary equivalent) to the server, not as a string. This way, there are no conversion errors. No matter what the value contains, it's never mixed with the query itself so it isn't executed. Even if address contained '); drop table Users;-- it wouldn't be executed.
Another option is to use a microORM like Dapper. Dapper uses reflection to map parameter names and data properties to create and execute parameterized queries:
var insertStmt="INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
"VALUES (#name,#email,#address)";
connection.Execute(insertStmt, new { name=someName,email=someEmail, address=someAddress});
As the project's page shows, you can execute the same query multiple times if you pass an array of parameters :
var myItems=new[]
{
new {name=someName,email=someEmail, address=someAddress}
};
connection.Execute(insertStmt, myItems);
You should use parameterized queries, for example if you are using ADO.NET, use this:
. . .
using(SqlConnection connection = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = #"INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress)
VALUES (#Name, #Email, #Address)";
cmd.Parameters.AddRange(new SqlParameter[]
{
new SqlParameter("#Name", name),
new SqlParameter("#Email", email),
new SqlParameter("#Address", address)
});
connection.Open();
cmd.ExecuteNonQuery();
}
. . .
other sql provider type examples you can find here.
I have tried the following code to save to a database. The condition is are, I have a value in a dropdown list and the values are New= 1, and old=2. If the user selects 1 or new then it will save data to database or if they select old then it will show the exist data.
Now this time my label shows data inserted but the data is not saved to the table (But doesn't show any error).
protected void btnsave_Click(object sender, EventArgs e)
{
if (ddl.Text=="1")
{
cs.Open();
string query = "insert into resig (#id,#name,#email) values('"+txtgn.Text+"','"+txtgname.Text+"','"+txtsg.Text+"')";
SqlCommand cmd = new SqlCommand(query,cs);
lbdmsg.Text = "Data Inserted";
//txtgname.Text = ddl.SelectedItem.ToString();
}
else
{
cs.Open();
string query = "select name, email from resig where id='" + txtgn + "'";
SqlCommand cmd= new SqlCommand(query,cs);
dr =cmd.ExecuteReader();
while(dr.Read())
{
string name= txtgname.Text;
string email=txtsg.Text;
}
cs.Close();
}
}
I see 2 things;
You are try to parameterize your column names, not your values.
You are not executing your insert command with ExecuteNonQuery().
You should use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
if (ddl.Text == "1")
{
string query = "insert into resig (id,name,email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query,cs);
cmd.Parameters.AddWithValue("#id", txtgn.Text);
cmd.Parameters.AddWithValue("#name", txtgname.Text);
cmd.Parameters.AddWithValue("#email", txtsg.Text);
cs.Open();
cmd.ExecuteNonQuery();
}
Call cmd.ExecuteNonQuery() to run the command on your db
Your SQL is both wrong, and very dangerous/susceptible to SQL injection. The first list in parenthesis must be a column list, and the values list should be parameters to avoid SQL injection:
string query = "insert into resig (id, name, email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query, cs);
cmd.Parameters.Add(new SqlParameter("#id", txtgn.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtgname.Text));
cmd.Parameters.Add(new SqlParameter("#email", txtsg.Text));
cmd.ExecuteNonQuery();
You should parameterize the select statement as well. Why is this important? Consider the resulting SQL if the user entered this for id and selected old:
'; delete resig; --
Building SQL by concatenating user input opens your database to the whim of users with bad intentions, and in this day and age should never be used. Countless web sites have been defaced and had their data corrupted -- it was ill-considered back in the day, but now we know better, and there's no excuse.
When I insert through the OleDbCommand with direct values no problem, it's working fine
OleDbCommand OleCmd1 = new OleDbCommand("Insert into My_Diary (sl_no,reminder) values("+a1+",'CHECK VALUE')", OleCon1);
OleCmd1->ExecuteNonQuery();
But when I like to update through parameter its showing "Syntax Error"....I can't identify my mistake...
string MyConStr = "Provider=VFPOLEDB.1; Data Source='C:\\For_Dbf'; Persist Security Info=False";
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (#sl_no,#reminder) ";
VFPDAp=gcnew OleDbDataAdapter();
VFPDApMy_Table1InsertCommand = gcnew OleDbCommand(InsSavDiaryCmd, OleCon1);
WithInsVar = VFPDAp.InsertCommand.Parameters;
WithInsVar.Add("#sl_no", OleDbType.Integer, 10, "sl_no");
WithInsVar.Add("#reminder", OleDbType.Char, 250, "reminder");
OleCon1.ConnectionString = MyConStr;
OleCon1.Open();
OleDbTransaction Trans=OleCon1.BeginTransaction();
//VFPDAp.DeleteCommand.Transaction = Trans;
//VFPDAp.UpdateCommand.Transaction = Trans;
VFPDAp.InsertCommand.Transaction = Trans;
VFPDAp.Update(MyDataTbl);
Trans.Commit();
OleCon1.Close();
The OleDbCommand doesn't use named parameters. You need to change the insert statement so that it uses questions.
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (?, ?) ";
You need to make sure that you have a parameter for each question mark and make sure that the parameters are inserted in order of their use in the insert statement.
** If you'd like to use name parameters... you can try using VfpClient which is a project that I'm working on to make data access a little nicer from .Net.
I have a this Items table in ms access
Items(Table)
Item_Id(autonumber)
Item_Name(text)
Item_Price(currency)
and i'm trying to insert a record using this code.
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString());
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values ('" + itemNameTBox.Text + "','" + Convert.ToDouble(itemPriceTBox.Text) + "')";
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myCon.Close();
Code is running without error but at the end no record is found in the table what mistake i'm doing?
Your sql insert text doesn't use parameters.
This is the cause of bugs and worse (SqlInjection)
Change your code in this way;
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString()))
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values (?,?)";
cmd.Parameters.AddWithValue("#item", itemNameTBox.Text);
cmd.Parameters.AddWithValue("#price", Convert.ToDouble(itemPriceTBox.Text));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
Of course this assumes that the text box for price contains a correct numeric value.
To be sure add this line before calling the code above
double price;
if(double.TryParse(itemPriceTBox.Text, out price) == false)
{
MessageBox.Show("Invalid price");
return;
}
then use price as value for the parameter #price
**EDIT 4 YEARS LATER **
This answer needs an update. In the code above I use AddWithValue to add a parameter to the Parameters collection. It works but every reader should be advised that AddWithValue has some drawbacks. In particular if you fall for the easy path to add just strings when the destination column expects decimal values or dates. In this context if I had written just
cmd.Parameters.AddWithValue("#price", itemPriceTBox.Text);
the result could be a syntax error or some kind of weird conversion of the value and the same could happen with dates. AddWithValue creates a string Parameter and the database engine should convert the value to the expected column type. But differences in locale between the client and the server could create any kind of misinterpretation of the value.
I think that it is always better to use
cmd.Parameters.Add("#price", OleDbType.Decimal).Value =
Convert.ToDecimal(itemPriceTBox.Text);
More info on AddWithValue problems can be found here