command.ExecuteNonQuery() - Incorrect syntax near ',' [duplicate] - sql

This question already has answers here:
What are good ways to prevent SQL injection? [duplicate]
(4 answers)
Closed 2 years ago.
I'm trying to create a Windows form that inserts data into my database when I type into it and click submit. It works for short things, but when I tried to type some longer sentences, it says this:
And here's the code:
private void SubmitButton_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Jokes VALUES('" + EnterJoke.Text + "', '" + EnterAnswer.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show(" Data Has Been Saved In Database ");
con.Close();
}
I get the error on this line:
cmd.ExecuteNonQuery();

Input text must be having a special character punctuation that is not being taken as part of the literal text as your code is doing a plain concatenation.
Try the below code that fixes two issues:
Most importantly, the SQL injection vulnerability.
Secondly, your issue (if it is something related to the input string having special characters)
private void SubmitButton_Click(object sender, EventArgs e)
{
SqlParameter joke = new SqlParameter();
joke.ParameterName = "#joke";
joke.SqlDbType = SqlDbType.VarChar;
joke.Value = EnterJoke.Text;
SqlParameter answer = new SqlParameter();
answer.ParameterName = "#answer";
answer.SqlDbType = SqlDbType.VarChar;
answer.Value = EnterAnswer.Text;
cmd = new SqlCommand("INSERT INTO Jokes VALUES(#joke, #answer)", con);
cmd.Parameters.Add(joke);
cmd.Parameters.Add(answer);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(" Data Has Been Saved In Database ");
con.Close();
}

Related

"Incorrect syntax near ')'."

I have a program that is to take a couple inputs and do stuff to them then store them in a local database (using SQL Server).
I have the following code for the connection:
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
String st = "INSERT INTO data(Username,Password, Hash, EncryptedPassword)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
cmd.ExecuteNonQuery();
con.Close();
It fails at the cmd.ExecuteNonQuery(); line, and throws this exception :
Incorrect syntax near ')'
I'm not even really sure where to start, as I haven't done any of this since college (107 years ago). Can anybody help me get started? I've been scouring but nothing seems to be working.
Maybe your insert should look like this:
INSERT INTO data (Username, Password, Hash, EncryptedPassword)
VALUES (#Username, #Password, #Hash, #EncryptedPassword)
The VALUES clause will need to be within the insert statement string. I would also recommend a using block instead of directly opening the SqlConnection, as will automatically close the connection upon exit whether by completion or error. While technically there isn't a difference between using String and string as in your command text, String would most often be used to reference a class while string is typically used in object references such as the case here.
string connectionString = #"YourConnectionString";
string st = "INSERT INTO data(Username,Password, Hash, EncryptedPassword) VALUES (#Username, #Password, #Hash, #EncryptedPassword)";
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(st1, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
con.Open();
cmd.ExecuteNonQuery();
}

I wrote an SQL SELECT statement that returns the entire table data rather then just the results that match my search

I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}

Adding new data error

When i'm running this code, it says:
String or binary data would be truncated. The statement has been
terminated.
On the underlined area, can some one help me with this.
namespace ASP_05
{
public partial class AddEmployee : System.Web.UI.Page
{
public DataSet getDataset(string query)
{
String sConn = "Data Source=(local);Initial Catalog=medewerkers;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(sConn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(query, conn);
da.Fill(ds);
da.Dispose();
return ds;
}
protected void toevoegen_Click(object sender, EventArgs e)
{
String vn = voornaam.ToString();
String an = voornaam.ToString();
String a = voornaam.ToString();
String t = voornaam.ToString();
string query = "INSERT INTO tblMedewerkers (voornaam, achternaam, afdeling, toestelnummer) VALUES ('" + vn + "','" + an + "','" + a + "','" + t + "')";
this.execSQL(query);
}
public int execSQL(string query)
{
String sConn = "Data Source=(local);Initial Catalog=medewerkers;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(sConn);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
}
The data that you are inserting in the table for a particular column is more in size than what you have defined in the table. Hence you are getting this error. Go through your column definitions and also through the records you are inserting and check if any of the column have less size than data you are inserting

c# - SqlReader of Read() not working

Problem: SqlReader of Read() not working
User Action:
enter their ID in a textbox and click a button
Program Action:
Select their name from database by given ID value
Then Print their name with HI! Message in RichTextBox or in Textbox
Error List:
No Error
Database:
Schema - dbo
Name - Sheet#Attendance
Here is my code:
private void swipe_button_Click(object sender, EventArgs e)
{
String ID_givenbyUSER = IDtxtBox.Text;
SqlConnection sqlConn = null;
sqlConn = new SqlConnection("Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=ABC_SchoolDB;Integrated Security=True");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
SqlDataReader sqlReader = cmd.ExecuteReader();
richTxtBox.Clear();
richTxtBox.AppendText("Hi buddy "); //This line works
while (sqlReader.Read())
{
richTxtBox.AppendText("Hi buddy "); //But,Its not work
pwdbox.Text = (sqlReader["Student_Name"].ToString()); //Its not work too
}
if (sqlConn != null)
{
sqlConn.Close();
sqlConn = null;
}
}
}
I think your problem is here:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
try this instead:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id='" + ID_givenbyUSER + "'", sqlConn);
Notice the part where you concatenate the single-quotes? It had spaces around them so your query would look like:
Where Serial_Id= ' Name '
The space in front of the user supplied value was probably causing your query to not return any rows.

Error with SQL command

I'm trying to get the users details in the text boxes in my form to my database in access, which should save. However i keep getting an error message every time i click to register, the following code is how i am trying to write it out:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
However I think that the problem is actually coming from this section:
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
Really your query is unreadable. Any kind of error could hide in that jungle of string concatenation and single quotes sprawled everywhere. (like a not necessary comma escaped probably from a fixup of a copy/paste operation)
You should use parameterized query and all of this will disappear
command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("#p1", txtSSN.Text);
command.Parameters.AddWithValue("#p2", txtName.Text );
command.Parameters.AddWithValue("#p3", txtCompany.Text);
command.Parameters.AddWithValue("#p4", _UserID);
command.ExecuteNonQuery();
Now I think that this is really more readable, no quotes to add because the framework knows the datatype of every parameter and will use the appropriate quoting required. Last but not least, no problem with Sql Injection