Error with SQL command - sql

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

Related

System.Data.SqlClient.SqlException: Incorrect syntax near "="

I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.

SQL entries not showing in graph

For a school project I am trying to produce a graph that shows me all the entries between two dates from an SQL table. I am using the following code:
int bLost = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strstartDate = sdf.format(startDate.getDate());
String strendDate = sdf.format(endDate.getDate());
try {
conn = JavaConnect.ConnecrDb();
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
+ " WHERE Datecreated >= " + strstartDate
+ " AND Datecreated <=" + strendDate );
rsLost = pst.executeQuery();
if (rsLost.next()) {
bLost = rsLost.getInt(1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Table cannot be found");
}
// this is some stuff for the graph
DefaultCategoryDataset bagStats = new DefaultCategoryDataset();
// This should show me how many entries it found
bagStats.setValue(bLost, "Bagage Lost", "Bagage Lost");
The code works fine if i do the statement without the date part like this:
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
I also tried using BETWEEN statements and it didn't work either.
I'm all out of ideas, I would really appreciate any help!
Caspar
You need to put quotes around the string in your sql code, so it reads as follows:
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
+ " WHERE Datecreated >= \'" + strstartDate
+ "\' AND Datecreated <=\'" + strendDate + "\'");
Whenever constructing sql statements, it is a good idea to print the string statement on the command line or in a message box while debugging, so you can see exactly what is being passed.
Also, if accepting user input into a variable, it is good practice to parameterize the query in order to avoid the possibility of sql injection attacks.

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.

edit the values of a database row that are displayed in textboxes

New to WPF. I want to edit the values of a database row that are displayed in textboxes. At the moment I am getting an error: "ExecuteNonQuery:Connection property has not been initialized". When I remove the where clause all rows are updated and not just the selected item.
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'");
cmd.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You haven't set the Connection property of SqlCommand. So the command does not know where to connect. Use the constructor overload from SqlCommand or set it separate like this
cmd.Connection = sc;
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'",sc); // add connection here
also You should use parametrized queries or Stored Procedures that will prevent SQL Injection attacks.
SqlCommand cmd = new SqlCommand("Update Rewards set Name = #name, Cost= #cost where Name = #name ,sc);
cmd.Parameters.AddWithValue("#name", Convert.ToString(this.txtName.Text)); and so on
I hope this is what you need :) Copy paste this. Good luck bro! :) If you have question, just ask, I'll answer if I know LOL :)
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
sql = "UPDATE REWARDS SET Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'WHERE Name = '" + this.txtName.Text +"'");
SqlCommand command = new SqlCommand(sql, con);
command.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Exception while retrieve a null field from sql ce 3.5

I am storing an image in a table in varbinary(max) format, actually first time it will be empty, I am checking whether it is empty of not but while checking for null field I am getting any exception stating invalid cast so can any one suggest what is the problem with this.
code sample is
con = new SqlCeConnection(CommonClass.ConnectionStringStartup);
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Signature,UserId FROM UserMaster Where " +
" LoginName = '" + UserName + "' " +
" AND Password = '" + Password + "'";
cmd.CommandType = CommandType.Text;
// MessageBox.Show(UserName);
SqlCeDataReader dr;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
if (dr.IsDBNull(0))
SignLoaded = false;
else
SignLoaded = true;
}
Thanks in advance
With regards
Bharath kumar
To me, it looks like this should work?
Have you tried Convert.IsDbNull( dr.GetValue(0))?
Otherwise I can only suggest using dr.GetValue(0) and look at the result.
Cheers