Error "Incorrect Syntax Near '/' - c#

I got a problem with my C#, whenever i try to save new data in the database coming from serial comm an error comes out and says
Incorrect Syntax Near '/'
I tried every suggestion everyone gave but it just wont stop..Here it is the piece of code where it comes out.
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SqlConnection cn = new SqlConnection(global::test_new.Properties.Settings.Default.Database3ConnectionString);
try
{
string sql = "INSERT INTO PowerData (Date/Time,Power(W)) values(" + this.powerTextBox.Text + ",'" + this.powerTextBox.Text + "'");
SqlCommand exeSql = new SqlCommand(sql, cn);
cn.Open();
exeSql.ExecuteNonQuery();
this.powerDataTableAdapter.Fill(this.database3DataSet.PowerData);
}
catch (Exception ex)
{
}
}

You need to escape special characters in table and column names like /
INSERT INTO PowerData ([Date/Time], Power(W)) values ...
In MySQL use backticks to escape, in MSSQL use brackets.

You've got some crazy column names there. If you want to include special characters in column names like that then you must wrap them in brackets in SQL, e.g. [Date/Time]. A better idea would be to not use such characters in the first place.

syntax should be like below, escape all columns with special characters
INSERT INTO PowerData
([Date/Time], [Power(W)])
VALUES
(GETDATE(), 'test1')
DEMO

First, "this.powerTextBox.Text" - I am guessing this shouldn't be the same value for both variables
change your code to this:
DateTime dt = DateTime.Parse(this.powerTextBox.Text);
string PowerW = this.powerTextBox.Text;
string sql = "INSERT INTO PowerData ([Date/Time],[Power(W)]) values(#val1, #val2);"
SqlCommand exeSql = new SqlCommand(sql, cn);
exeSql.Parameters.AddWithValue("#val1", dt);
exeSql.Parameters.AddWithValue("#val2", PowerW);
cn.Open();
exeSql.ExecuteNonQuery();

Related

Error: wrong syntax near '_1_txt'

Unfortunately my Code does not work: It always throws the error: Wrong syntax near '_1_txt'. Thanks in advance!
This is my Code:
protected void btnSpeichern_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO tbl_mag(1_1_txt) VALUES(#1_1_txt)";
{
cmd.Parameters.AddWithValue("#1_1_txt", txt1.Text.Trim());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
Column names generally shouldn't (or in some cases can't) begin with a number. Ideally you should change your schema to follow this rule, but if you can't then at the very least you would need to explicitly specify the name as an identifier. In SQL Server that's done with square brackets:
INSERT INTO [tbl_mag] ([1_1_txt]) VALUES (#1_1_txt)
This maybe answered by this post:
Syntax Error when the column name contains underscore
Basically you have to Sql Escape the columns names by wrapping them in square brackets.
1_1_txt --> [1_1_txt]

What is wrong with this query, its show only increment, assignment etc can be used as argument?

Check the bold oledb command, idont know what kind of error it is , or what im doing wrong
please help :(
private void button1_Click(object sender, EventArgs e)
{
try
{
string constring = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\ShahMuhammad\Desktop\testLogin.accdb; Persist Security Info=True;";
OleDbConnection conDataBase = new OleDbConnection(constring);
***OleDbCommand cmdDatabase = new OleDbCommand("Select * from login where uname="this.textBox1.Text" and pword = "this.textBox2.Text", connDatabase);***/// HERE I HAVE PROBLEM
OleDbDataReader myReader;
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
int count=0;
while(myReader.Read())
{count=count+1}
if(count==1)
{MessageBox.Show("Successfull Login");}
else if (count >1)
{MessageBox.Show("Duplicate Uname or Password");}
else
MessageBox.Show("Ghalat input ustaad, wari account password");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
kindly tell me whats is the error , i am a total newbie in C# programming, specially connecting with db
You have a problem because uname and pword are text fields.
When you query text fields you need to put the values between single quotes.
However there is a better solution and it is called Parameterized query
OleDbCommand cmdDatabase = new OleDbCommand(#"Select * from login
where uname=#name and pword = #pword",
connDatabase);
cmdDatabase.Parameters.AddWithValue("#name", textBox1.Text);
cmdDatabase.Parameters.AddWithValue("#pword",textBox2.Text);
....
No more problems with quoting string, replacing single quotes inside strings and Sql Injection attacks, and your command text is now a lot more readable.
When you have fixed this problem I also suggest to read about the weakness of storing passwords in clear text inside a database. In your case a malicious user can simply copy the database and he/she can easily read all your users passwords.
EDIT
Revisiting this question after an hour and I see that there are multiple correct answers (Soner Gönül and Paul Zahra) to your question (albeit incomplete including mine).
In a summary:
Concatenating strings in C# is done using the + operator
There is a typographical error in your naming the connection
Passing string values to a database should be done enclosing strings
in quotes
Use the using statement around disposable objects
Finally use a parameterized query when dealing with command texts
"Select * from login where uname="this.textBox1.Text" and pword = "this.textBox2.Text"
I think this should be;
"Select * from login where uname=" + this.textBox1.Text + "and pword =" + "this.textBox2.Text
If your columns are not character typed, othwerwise you need to use single quotes with them.
But as a better way, always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
var cmdDatabase = new OleDbCommand("Select * from login where uname= ? and pword = ?", connDatabase);
cmdDatabase.Parameters.Add("p1", OleDbType...).Value = this.textBox1.Text;
cmdDatabase.Parameters.Add("p2", OleDbType...).Value = this.textBox2.Text;
And use using statement to dispose your OleDbCommand, OleDbConnection and OleDbDataReader. Like;
using(OleDbConnection conDataBase = new OleDbConnection(constring))
using(OleDbCommand cmdDatabase = conDataBase.CreateCommand())
{
...
...
using(OleDbDataReader myReader = comm.ExecuteReader())
{
//
}
}
Finally, looks like you store your passwords as a plain text. Don't do that! Read: Best way to store password in database
You have two issues with your code... as others have pointed out you need to concatenate the strings... the other is your db connection object, it is called conDataBase but you reference connDataBase and your sql string is a bit squiffy ... your code should look like...
OleDbConnection conDatabase = new OleDbConnection(constring);
string sql = "Select * from login where uname='" + this.textBox1.Text + "' and pword = '" + this.textBox2.Text + "'"
OleDbCommand cmdDatabase = new OleDbCommand(sql, conDatabase);
but as others have said using a parameterised query is safer.
you should write 'this.textbox1.text' (+this.textbox1.text+)
ur query should be like this
"select * from TblLogin where UserName='"+this.txtUserName.text+"' and Password='"+this.txtPassword.text+"' ";

Conversion failed when converting date and/or time from character string C#

I would like a help please. When I want insert datetimepicker value into my table but he doesn't can insert and he show me a message
Conversion failed when converting date and/or time from character
string
You can help me please !
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void add_Click(object sender, EventArgs e)
{
cmd.CommandText = "Insert into clients values (" + cintxt.Text + ", '" + nomtxt.Text + "', '" + prntxt.Text + "', '" + datenaiss.Value + "', '" + addtxt.Text + "', '" + teltxt.Text + "')";
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
}
Your code that tries to insert the record should be changed to use a parameterized approach.
This could be an example
private void add_Click(object sender, EventArgs e)
{
string commandText = #"Insert into clients values
(#id, #name, #prn, #datan, #addr, #tel)";
using(SqlConnection cnx = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(commandText, cnx)
{
cmd.Parameters.AddWithValue("#id", Convert.ToInt32(cintxt.Text));
cmd.Parameters.AddWithValue("#name", nomtxt.Text);
cmd.Parameters.AddWithValue("#prn", prntxt.Text);
cmd.Parameters.AddWithValue("#datan", datenaiss.Value);
cmd.Parameters.AddWithValue("#addr", addtxt.Text);
cmd.Parameters.AddWithValue("#tel", teltxt.Text );
cnx.Open();
cmd.ExecuteNonQuery();
}
}
In this code I have changed something. First, the connection and the command are no more global variables but just local and are enclosed in a using statement that ensure a proper closing and disposing also if, for any reason, the code throws an exception.
Second the command text is no more a concatenation of strings, but it is only a single string with parameters placeholders. Concatenating string to build command texts is really a bad practice. Sql Injection hackers wait for commands built in this way to hit your database and, as you have already seen, more often than not, the underlying datatable doesn't understand a string that represent a date to be a valid date.
Finally the command parameters collection is filled with a parameter for every field expected by the command text placeholders. Notice that in this way you build parameters that are of the datatype of the value passed not simply strings that are not expected by the datatable fields. Of course in your actual situation it is possible that some of these parameters should be changed to match exactly your datatable field (for example I don't know id the first field is an integer or not)
EDIT As requested by comments below I add also some considerations on the method AddWithValue.
While it is convenient and expressive it could be a problem if your program call this code with frequency or if your database is under heavy use. The preferred method to use is
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = nomtxt.Text;
.....
See MSDN SqlParameterCollection.Add
and more info about the difference between Add and AddWithValue are explained here
How Data Access Code Affects Database Performance

SQL syntax error manual check

For the code below I get the error
You have an error with your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name','Score') VALUES('cain','0') at line 1
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=bel.sunderland.ac.uk; " +
"database=bg30xw; " +
"uid=USERNAME; " +
"pwd=PASSWORD;";
string query = "INSERT INTO highscore('Name','Score') VALUES (#Name, #Score);";
using(MySqlConnection myconn = new MySqlConnection(connStr))
{
Console.WriteLine(query);
MySqlCommand insertCommand = new MySqlCommand(query,myconn);
insertCommand.Parameters.AddWithValue("#Name",sName);
insertCommand.Parameters.AddWithValue("#Score",iTotalScore);
try
{
myconn.Open();
insertCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
myconn.Close();
}
The error showed up in the 'messagebox.show(ex.message);' when I ran the program. I looked on google but most of the suggestions was for quotation marks, I have changed and re-changed them but to no avail.
Thanks
Use backticks to escape column (and table) names, not quotes
INSERT INTO highscore(`Name`,`Score`) VALUES (#Name, #Score)
Single-word column names don't need to be escaped (I don't think MySQL allows it, but I may be wrong);therefore, this should work:
INSERT INTO highscore(Name,Score) VALUES (#Name, #Score);
You may give an alias to a column, using spaces when you run a select statement, but I simply avoid them in general.

Count from SQL Rows into C# textbox

Hi there its the first time to use stackoverflow so hi every one L)
i'm a beginner into C# forms i take it as a fun hobby.
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
Int32 count = (Int32)comm.ExecuteScalar();
textbox2.Text ="Found "+ count+" Members;
well its just a mix between 2 codes i have got from google xD
how ever the error appear here textbox2.Text ="Found "+ count+" Members;
There are a couple of things wrong with this line of code:
textbox2.Text ="Found "+ count+" Members;
First of all, there's a syntax error. You never close the second set of quotes. You'd do so like this:
textbox2.Text ="Found "+ count+" Members";
However, string concatenation like this is still a little messy. You have two literal strings and you're trying to add them to an integer, which isn't entirely intuitive (and probably slower than it needs to be). Instead, consider using a formatting string:
textbox2.Text = string.Format("Found {0} Members", count);
This will take the value from count (which is an integer) and, internally to the string.Format() function, discern its string representation and insert it into the placeholder in the formatted string.
UPDATE: That takes care of the compile-time errors. Now you're going to get a run-time error from this:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
As soon as you try to execute that SQL statement you're going to get an error from the database because the resulting query has a syntax error:
SELECT COUNT(*) FROM Members where sponser = some text'
You're missing the opening single-quote for the parameter. Something like this:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = '"
+textbox1.text+"'", connection);
However, and this is important, you're still not done. This line of code is wide open to a very common and easily exploitable vulnerability called SQL Injection. You'll want to move away from direct string concatenation and use parameters for your SQL queries. Something like this:
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = #sponser");
cmd.Parameters.Add("#sponser", textbox1.text);
Int32 count = (Int32)comm.ExecuteScalar();
Know that there is still a lot more you can do to improve this, which is all worth learning over time. Things you can look into are:
Checking and validating user input (textbox1.text) before you even try to use it in a SQL query.
Checking the output of comm.ExecuteScalar() before trying to directly cast it to an Int32 (this would give you a runtime error if it returns anything other than an integer for some reason).
Consider using something like Linq to Sql in place of ADO.NET components as it does a lot more for you with less code on your part.
protected void Page_Load(object sender, EventArgs e)
{
lb1.Text = GetRecordCount(textbox2.Text).ToString();
}
private int GetRecordCount(string myParameter)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();
Int32 count = 0;
string sql = "SELECT COUNT(*) FROM members WHERE sponsor = #Sponsor";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Sponsor", SqlDbType.VarChar);
cmd.Parameters["#Sponsor"].Value = myParameter;
try
{
conn.Open();
count = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
}
}
return (int)count;
}
You are missing a closing " at the end:
textbox2.Text ="Found "+ count+" Members";
You code is vulnerable to SQL Injections. Please consider using Parameters.
private int GetMemberCount(string connectionString, string sponsor)
{
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM members WHERE sponsor = #Sponsor";
command.Parameters.AddWithValue("#Sponsor", sponsor);
return Convert.ToInt32(command.ExecuteScalar());
}
}
//Usage
var sponsor = textbox1.text;
var count = GetMemberCount(connectionString, sponsor);
textbox2.Text = string.Format("Found {0} Members", count);

Categories