I am trying to get a string from a MS Access database and insert into a SQL Server database by using a dataset. But the utf8 string in my SQL statement inserted like ????????? - what can I about this?
This is my code:
OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access);
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "t_about_us");
con.Open();
string command2 = "insert into t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) values('" +
Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(ds2.Tables[0].Rows[0]["matn"].ToString())) + "','" +
Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString()) + "','" +
ds2.Tables[0].Rows[0]["metatag_description"].ToString() + "','" +
ds2.Tables[0].Rows[0]["metatag_keywords"].ToString() + "','" +
ds2.Tables[0].Rows[0]["metatag_author"].ToString() + "')";
SqlCommand cmdd2 = new SqlCommand(command2, con);
cmdd2.ExecuteNonQuery();
con.Close();
By using dynamic SQL to construct an SQL statement with sting literals like 'this' you are implicitly converting the string from Unicode into the single-byte character set used by the SQL Server, and any Unicode characters that do not map to that target character set will be replaced by question marks.
So, for example, with my SQL Server ...
cmd.CommandText = "INSERT INTO myTable (textCol) VALUES ('γιορτή')";
cmd.ExecuteNonQuery();
... will be inserted as ...
????t?
... even though [textCol] is defined as an NVARCHAR column.
The correct approach is to use a parameterized query, like so
cmd.CommandText = "INSERT INTO myTable (textCol) VALUES (#word)";
cmd.Parameters.Add("#word", System.Data.SqlDbType.NVarChar).Value = "γιορτή";
cmd.ExecuteNonQuery();
thank you my friends Finally my code work, this is answer:
OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access);
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "t_about_us");
con.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) VALUES (#matn,#see,#metatag_description,#metatag_keywords,#metatag_author)",con);
cmd1.Parameters.Add("#see", System.Data.SqlDbType.BigInt).Value = Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString());
cmd1.Parameters.Add("#matn", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["matn"].ToString();
cmd1.Parameters.Add("#metatag_description", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_description"].ToString();
cmd1.Parameters.Add("#metatag_keywords", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_keywords"].ToString();
cmd1.Parameters.Add("#metatag_author", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_author"].ToString();
cmd1.ExecuteNonQuery();
con.Close();
Related
I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.
I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.
Hi guys when I want to update without changing old data I get this error
Syntax error (missing operator) in query expression 'data.[Phone Number]+ ' ' +0770444 +'.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET data.[Phone Number] = data.[Phone Number]+ ' ' +"+textBox23.Text+" + WHERE data.([ID]) = " + textBox15.Text + " ";
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt;
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Data Updated Successfully");
con.Close();
Start using Command Parameters and you will avoid problems like this:
cmd.CommandText = #"UPDATE data SET [Phone Number] = [Phone Number] + ' ' + #NewPhoneNumber WHERE ID = #ID ";
cmd.Parameters.AddWithValue("#ID", textBox15.Text);
cmd.Parameters.AddWithValue("#NewPhoneNumber", textBox23.Text);
cmd.Connection = con;
Also this will protect you from Sql Injection. Be aware you should provide proper naming of your controls(textboxes), this names means nothing for other programmers. Write your columns together PhoneNumber it is annoying to escape them all the time, you are creating more work for yourself for no reason.
Other points wrap your OleDbConnection and OleDbDataAdapter in using blocks
using(OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb"))
{
con.Open();
//... stuff
DataTable dt;
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
//stuff relate to db adapter
}
}
Using is representing try/catch/finally with calling Dispose() in finally block. This will protect if your code have an exception your connection will be closed. In your current format this is not happening. OleDbDataAdapter is using unmanaged resources so it should be Dispose() too.
Your command seems to be wrong it should be
cmd.CommandText = "UPDATE data SET data.[Phone Number] = " + "'" + data.[Phone Number] + textBox23.Text + "' WHERE data.([ID]) = " + textBox15.Text;
Whereas it is always recommended that we should use the Parameterized Query instead of string concat.
thanks guys I resolved it by this
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET [Phone Number] = [Phone Number]+\n'" + textBox3.Text + "' WHERE ID = " + textBox15.Text + " ";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New Number Inserted Successfully to ID " + textBox15.Text);
con.Open();
this is my code:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=MSDAORA;Data Source=data;Password=ss8_pakhsh;User ID=SHIFTS_N";
con.Open();
int MAXID = 1175;
MAXID++;
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(" + MAXID + ",'"
+ textBox1.Text +
"', SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME="+comboBox1.Text;
OleDbDataAdapter oda = new OleDbDataAdapter(sqlcommand, con);
oda.Fill(dt);
con.Close();
while i running it ,gets this error :
One or more errors occurred during processing of command.
i think my query has problem because when i enter it on TOAD editor(for oracle) gets me this error:
ORA-00936: missing expression
You were missing quotes and paranthesis in your query.
SQL Injection Alert
To avoid this you should use Parameterized queries as like follows
string sqlcommand ="INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID)
VALUES(?,?,SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=?)";
OleDbConnection oledbConnection = new OleDbConnection(con);
OleDbCommand oledbCommand = new OleDbCommand(sqlcommand , oledbConnection);
oledbCommand.Parameters.AddWithValue("?", txtquotationno.Text);
oledbCommand.Parameters.AddWithValue("?", cmbjobcode.Text);
oledbCommand.Parameters.AddWithValue("?", comboBox1.Text);
OleDbDataAdapter oda = new OleDbDataAdapter(oledbCommand);
DataTable dt= new DataTable();
oda.Fill(dt);
You need to put your select query in braces as you are selecting this from another table so this shoould be in (). Also Department_Name looks of type varcharso its value should be in single quotes. Change your query like this.
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(" + MAXID + ",'"
+ textBox1.Text +
"',(SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME='"+comboBox1.Text+"'"));
Also use parameterized query to prevent sql injection.
I have this peace of code where I need to retrieve data from Mysql. If I use parameterized query it does not take actual parameter value instead it takes parameter name as value.
Error: #choise must be defined
MySqlConnection connection = new MySqlConnection("");
MySqlDataAdapter mySqlDataAdapter;
DataSet DS;
private string columnValue = xxx;
private string Choise = yyy;
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table2 WHERE " + columnValue + " = #choise";
command.Parameters.Add(new MySqlParameter("#choise", Choise));
DS = new DataSet();
connection.Open();
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
mySqlDataAdapter.Fill(DS);
connection.Close();
when I run this i get query like:
SELECT * FROM table2 WHERE xxx = #choise
instead of
SELECT * FROM table2 WHERE xxx = yyy.
Where is the problem?
I have tried:
command.Parameters.Add(new MySqlParameter("#choise", Choise));
command.Parameters.AddWithValue("#choise", Choise);
It works fine when I'm using actual variables instead of parameters.
I think you need to run Prepare() on the command before adding parameters:
command.CommandText = "select * from table2 where " + columnValue + " = #choise";
command.Prepare();
command.Parameters.AddWithValue("#choise", Choise);
Try this instead:
command.CommandText = "SELECT * FROM `table2` WHERE `" + columnValue + "` = #choise";
command.Parameters.AddWithValue("#choise", Choise);