I tried some of your suggestions but still the same error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' (size int(5))' at line 1
Here is my code:
try{
query = "CREATE TABLE #name (size int(5))";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = txtboxName.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
i think you intended to use backticks `` to escape table name but used single quotes instead.
query = "CREATE TABLE `"+ txtboxName.Text + "`(size int(5))";
I would try to add escape sequences to txtboxName.Text. There can be some special characters, that break your SQL statement.
You missed space between table name and the column definitions
query = "CREATE TABLE "+ txtboxName.Text + " (size int(5))";
|
put space here
sql injection... don't use inline parameters. below is sample code with few best practices what I know. But you can't use parameters for table names.
public void CreateTable(string tblName)
{
using (var con = new MySqlConnection(MySqlConnectionString))
{
using (var cmd = new MySqlCommand(String.Format("CREATE TABLE {0} (size int(5))",tblName), con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
}
Related
I'm trying to add something so that things can be deleted from a table, though it says there is a syntax error near '=' and I can't seem to spot it. I know this isn't the most ideal way to be doing this, but I've been told to do it this way.
Here's what I've put:
Con.Open();
string query = "DELETE FROM tablepassengers WHERE passportno.=" + tbpassno.Text + ';';
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
Con.Close();
populate();
As you said the . is meant to be there and that the column name is passportno., this is where your problem is. It's not something that is expected, or recommended, but it is something that can be handled.
When using Sql you really should be using Parameters when constructing Sql statements in code. It is strongly suggested, not only is it good practice it will protect your applications from targetted attacks, to use Parameters -- Please read Why do we always prefer using parameters in SQL statements?
Change your code to look like this:
string query = "DELETE FROM tablepassengers WHERE [passportno.]=#passportNo;";
using (SqlCommand cmd = new SqlCommand(query, Con))
{
cmd.Parameters.Add(new SqlParameter("passportNo", SqlDbType.VarChar, 100).Value = tbpassno.Text;
cmd.ExecuteNonQuery();
}
MessageBox.Show("deleted");
Con.Close();
try
{
string query = "DELETE FROM tablepassengers WHERE passportno=" + tbpassno.Text;
SqlCommand cmd = new SqlCommand(query, Con);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
}
catch (SqlException ex)
{
MessageBox.Show("Error\n" + ex.Message);
}
finally
{
Con.Close();
}
I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error.
"Data type mismatch in criteria expression."
i'm sure it's something with the ' x ' i put in my query but still can't figure out what is THE problem.
it's (int,int,string,string,string,int,int,string,int,int) format
string SqlStr = string.Format("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values({0},{1},'{2}','{3}','{4}',{5},{6},'{7}',{8},{9})", s.ClientId,s.OrderId,s.Date,s.CardTyp,s.PayMethod,s.Ex_Y,s.Ex_M,s.CcComp,s.CcNum,s.TotalSale);
Thanks for your help.
String.Format will not be a good approach for building queries. I suggest you to use, Parameterised queries that helps you to specify the type too and also its more helpful to prevent injection: Here is an example for you:
string query = "insert into Orders" +
"(client_id,order_id,date_,card_typ,...)" +
" values(#client_id,#order_id,#date_,#card_typ...)";
using (SqlCommand sqCmd = new SqlCommand(query, con))
{
con.Open();
sqCmd.Parameters.Add("#client_id", SqlDbType.Int).Value = s.ClientId;
sqCmd.Parameters.Add("#order_id", SqlDbType.VarChar).Value = s.OrderId;
sqCmd.Parameters.Add("#date_", SqlDbType.DateTime).Value = s.Date;
sqCmd.Parameters.Add("#card_typ", SqlDbType.Bit).Value = s.CardTyp;
// add rest of parameters
//Execute the commands here
}
Note: I have included only few columns in the example, you can replace ... with rest of columns.
Please dont use a concatenation string ...
Here is an example :
using (SqlConnection connection = new SqlConnection("...connection string ..."))
{
SqlCommand command = new SqlCommand("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values(#client_id,#order_id,#date_,#card_typ,#pay_mthd,#ex_y,#ex_m,#cc_comp,#cc_num,#t_sale)", connection);
SqlParameter pclient_id = new SqlParameter("#client_id", System.Data.SqlDbType.Int);
pclient_id.Value = 12;
command.Parameters.Add(pclient_id);
SqlParameter pcard_typ = new SqlParameter("#card_typ", System.Data.SqlDbType.VarChar);
pcard_typ.Value = "some value";
command.Parameters.Add(pcard_typ);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
Okay basically I have a SQL Server database that has details in it.
Column names: Student_Id, Student_name, Unit_number, Unit_grade
I would like to query this database using two textboxes where you enter the id and unit_number and it will return the results in a message box when a button is clicked.
Where the question marks in the code are is where I am unsure of how to display a message box with the result. Unless this is completely the wrong way of doing things, I am only starting out with SQL in C#
I shouldn't be prone to SQL Injection using parameters as far as I know?
try
{
string str = "SELECT * FROM Students WHERE (Student_Id, Unit_number LIKE '%' + #search + '%')";
SqlCommand command = new SqlCommand(str, connect);
command.Parameters.Add("#search", SqlDbType.NVarChar).Value = textBox1.Text;
command.Parameters.Add("#search", SqlDbType.NVarChar).Value = textBox2.Text;
connect.Open();
command.ExecuteNonQuery();
SqlDataAdapter dataAdapt = new SqlDataAdapter();
dataAdapt.SelectCommand = command;
DataSet dataSet = new DataSet();
dataAdapt.Fill(dataSet, "Student_Id, Unit_number");
//?
//?
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your SQL is wrong in that your WHERE clause is syntactically incorrect. You probably want something like:
string str = "SELECT * FROM Students WHERE Student_ID = #id AND " +
"Unit_number LIKE #search";
This assumes that Student_ID is a text type. The syntax would be slightly different if it was a number.
You are trying to add the same parameter to the query twice, which you won't want. Instead you'd want two parameters to match with the new SQL definition:
command.Parameters.Add("id", SqlDbType.NVarChar).Value =
textBox1.Text;
command.Parameters.Add("search", SqlDbType.NVarChar).Value =
"%" + textBox2.Text + "%";
Running ExecuteNonQuery on the SqlCommand object doesn't do much for you as it is a query and you're not asking for the result back.
If you're only expecting one table back from your query, you'd probably be better off with a DataTable rather than a DataSet (the DataSet can contain many tables which is overkill for what you need).
try
{
string str = "SELECT * FROM Students WHERE Student_Id = #id AND " +
"Unit_number LIKE #search";
connect.Open();
SqlCommand command = new SqlCommand(str, connect);
command.Parameters.Add("id", SqlDbType.NVarChar).Value =
textBox1.Text;
command.Parameters.Add("search", SqlDbType.NVarChar).Value =
"%" + textBox2.Text + "%";
SqlDataAdapter dataAdapt = new SqlDataAdapter();
dataAdapt.SelectCommand = command;
DataTable dataTable = new DataTable();
dataAdapt.Fill(dataTable);
// At this point you should have a DataTable with some results in it.
// This is not going to be the best way of displaying data,
// but it should show you _something_
// It just iterates through the rows showing the columns
// which you've shown as being in your data.
foreach (DataRow dr in dataTable.Rows)
{
MessageBox.Show(String.Format("{0} - {1} - {2} - {3}",
dr["Student_Id"], dr["Student_name"],
dr["Unit_number"], dr["Unit_grade"]));
}
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
EDITED to change the parameter handling as it didn't quite do what was needed. The % symbols are not part of the parameter rather than the SQL string.
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
using (var conexao = Conexao())
{
conexao.Open();
string rotaloja = Convert.ToString(dtExcel.Rows[i][1]) + Convert.ToString(dtExcel.Rows[i][0]);
string bn = "select * from Emb where ROTALOJ= #rotaloja";
OleDbCommand cmd1 = new OleDbCommand(bn, conexao);
cmd1.Parameters.AddWithValue("#rotaloja", rotaloja);
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
using (OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read())
{
try
{
string cmdText = "UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja";
conexao.Open();
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
try
{
string cmdText = "INSERT INTO Emb (ROTALOJ , ROTA, LOJA, QTDEEMBAL) VALUES (#rotaloja,#p0,#p1,#p2)";
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
//////////////////////////////////////////////////////////////////////////////////////////////
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
}
}
I am doing import excel to database more when he does select to see if you have the information in the database is giving error can be? for those who help me thank you
Img : http://i.stack.imgur.com/qxQDm.png
You created a new query Queryyy and assumed that the parameters attached with previous query cmd1 would be available with your command string bn. You need to add parameter to your query Queryyy
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Query.Parameters.AddWithValue("#rotaloja", rotaloja); //here
using (OleDbDataReader drr = Queryyy.ExecuteReader())
//.......rest of your code
}
Consider using helpful variable names.
In your current code, you added parameter to a cmd1 which is independent of Queryyy. In your new query Queryyy, you are using command text which requires a parameter and since you are not passing it, you are getting the exception.
Take a look at : OleDbCommand.Parameters Property, You may have to pass the parameter with ?, since it doesn't seem to support named parameters.
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
You're not setting the value of #rotaloja in this query:
"UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja"
OleDBCommand does not support names parameters. Replace your parameters with ? in each SQL statement and add the parameters in the order that they appear in the query.
I am using VS 2008 and SQL Server 2005. I am using below code to insert a row to a table.
Table is TestTable, and it has a single column Name (varchar(50)).
I am new to C# coding.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string sql = "insert into TestTable(Name) values (vinayak)";
using (SqlConnection conn = new SqlConnection("Data Source=VINAYAK-PC;Initial Catalog=TestTable;Integrated Security=True;"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Name", "test"); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
}
You haven't included the parameter in the SQL statement.
Change vinayak to #Name.
In table "TestTable" if you have only one column "Name" and you want to insert value "vinayak" in that then include vinayak in single quotes and you do not need to execute following statement -:
cmd.Parameters.AddWithValue("#Name", "test");
if you want to use parameter in your sql command then make sure u prefix "#" before "name" in your sql command.
see this link