return student information - SQL/C# assignment - c#

so essentially, I have two text fields, one with the firstName and one with the lastName of the student. What I want the program to do is this:
return the student's phone number and comments using the firstName and lastName from the TextBox above. This is what I have so far:
if (actionButton.Text == "Update")
{
SqlConnection cn;
cn = new SqlConnection();
cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
cn.Open();
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE #firstName AND lastName LIKE #lastName"; //AND lastName LIKE #lastName"
//used this part to delete records
SqlParameter param = new SqlParameter();
param.ParameterName = "#firstName";
param.Direction = ParameterDirection.Input;
param.SqlDbType = SqlDbType.VarChar;
param.Value = firstNameTB.Text;
cmd.Parameters.Add(param);
param.ParameterName = "#lastName";
param.Direction = ParameterDirection.Input;
param.SqlDbType = SqlDbType.VarChar;
param.Value = lastNameTB.Text;
cmd.Parameters.Add(param);
//display data in a listbox
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
string s;
s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
MessageBox.Show(s);
}
cmd.ExecuteNonQuery();
cn.Close();
}
I'm not sure where to go from here. In the code I have placed two comment statements, so I have used the above in two different parts of my assignment, but when I bring them together, it doesn't work.
what is happening is that I am not getting any results. Essentially I need it to give me the phone number and comments of the student indicated in the two text boxes

I assume you're getting an error, yes? You are trying to do two operations on the same command object and my hazy recollection says that's not going to work. Try removing this line.
cmd.ExecuteNonQuery();
If you have studied the using statement, that's typically a better solution for handling resources like your connection and reader.

if (actionButton.Text == "Update")
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
cn.Open();
MessageBox.Show(cn.ConnectionState.ToString());
// If you are shown "Open" by above messagebox and you are using correct table and column names then you will get accurate results by following code
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE '" + firstNameTB.Text + "' AND lastName LIKE '" + lastNameTB.Text + "' ";
SqlDataReader reader = cmd.ExecuteReader();
string s = "";
while (reader.Read())
{
s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
MessageBox.Show(s);
}
cn.Close();
}

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.' on Datatable and object

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.

MS Access Update Query Not Working

I can't Figure out what is wrong with the query, but it is not updating any value in the Table
string qry = "UPDATE Stock SET Itemname=#n,Unit=#u,Price=#p,Tax=#t,Balance=#b,Status=#s Where Sid=#sid";
OleDbCommand ocmd = new OleDbCommand(qry,BBC);
ocmd.Parameters.AddWithValue("#n", name);
ocmd.Parameters.AddWithValue("#u", unit);
ocmd.Parameters.AddWithValue("#p", price);
ocmd.Parameters.AddWithValue("#t", tax);
ocmd.Parameters.AddWithValue("#b", balance);
ocmd.Parameters.AddWithValue("#s", status);
ocmd.Parameters.AddWithValue("#sid", sid);
ocmd.ExecuteNonQuery();
Price,Tax and Balance are Decimal values.
I did debug and its working fine but just not updating the value.
set the type of each parameter and execute the query.
List<OleDbParameter> paramList = new List<OleDbParameter>();
OleDbParameter param = new OleDbParameter("#param", OleDbType.TypeName);
param.Value = value;
paramList.Add(param);
ocmd.Parameters.AddRange(paramArray);
I think this will do it for you.
string ConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\your_path_here\test.accdb";
using(OleDbConnection conn = new OleDbConnection(ConnString ))
using(OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = # "UPDATE Stock SET Itemname=#n,Unit=#u,Price=#p,Tax=#t,Balance=#b,Status=#s Where Sid=#sid";
cmd.Parameters.AddWithValue("#n", txtItemName.Text);
cmd.Parameters.AddWithValue("#u", txtUnit.Text);
cmd.Parameters.AddWithValue("#p", Convert.ToDecimal(txtPrice.Text));
cmd.Parameters.AddWithValue("#t", Convert.ToDecimal(txtTax.Text));
cmd.Parameters.AddWithValue("#b", Convert.ToDecimal(txtBalance.Text));
cmd.Parameters.AddWithValue("#s", txtStatus.Text);
cmd.Parameters.AddWithValue("#sid", txtSID.Text);
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}

Weird error in "insert into" command?

I know this may sound rubbish but that's the truth.
everytime when i try to run this code i get syntax error.
any idea why?
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Rock.accdb";
con.Open();
String query = "insert into category ([name],desc) values (#1,#2)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#1", textBox1.Text);
cmd.Parameters.AddWithValue("#2", textBox2.Text);
cmd.ExecuteNonQuery();
textBox1.Text = null;
textBox2.Text = null;
label4.Text = "New Category Created";
label4.ForeColor = Color.Green;
the error is: Syntax error in INSERT INTO statement # cmd.ExecuteNonQuery();
desc is also a keyword (for descending) and so you'd need:
String query = "insert into category ([name],[desc]) values (#1,#2)";
Change your insert query like this,
String query = "insert into category ([name], [desc]) values (#1,#2)";
desc is reserved word by default. Also, please close your connection by con.Close(); after executing the command.

I am having trouble inserting into my database with c#

I get this error when trying to insert data into my database.
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'User'.
Here is the code:
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(
Properties.Settings.Default.BlackBookDBConnectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO User (Username, Password, SecurityQuestionOne, "
+ "SecurityQuestionTwo, SecurityAnswerOne, SecurityAnswerTwo); VALUES ("
+ txtRegisterUsername.Text + ","
+ txtRegisterPassword.Text + ","
+ lstRegisterSecurityQuestionOne.SelectedText + ","
+ lstRegisterSecurityQuestionTwo.SelectedItem + ","
+ txtRegisterSecurityAnswerOne.Text + ","
+ txtRegisterSecurityAnswerTwo.Text + ")";
cmd.CommandText = "INSERT INTO USer ()";
cmd.Connection = connection1;
connection1.Open();
cmd.ExecuteNonQuery();
connection1.Close();
}
I have edited my code. However it still does not insert anything into my database for some reason.
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (#Username,#Password,#QuestionOne,#AnswerOne,#QuestionTwo,#AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("AnswerTwo", answerTwo);
command.Connection = connection1;
connection1.Open();
command.ExecuteNonQuery();
connection1.Close();
}
Remove this line:
cmd.CommandText = "INSERT INTO USer ()";
EDIT
After looking at your new code, you have wrong parameters names (missing #). You should change your code to this:
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("#Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("#Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("#QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("#QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("#AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("#AnswerTwo", answerTwo);
Remove second line assigning cmd.CommandText - it's overwriting the first one
User is a keyword in SQL server, if you have a table with that name (which you should not) enclose it into square brackets:
cmd.CommandText = "INSERT INTO [User] ...
On a side note - learn about parametrized queries. They're a great way to avois SQL injection attacks (not to mention confusing mess of string concatenation)
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
connection1.Open();
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (#Username,#Password,#QuestionOne,#AnswerOne,#QuestionTwo,#AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.Add("#Username", SqlDbType.VarChar, 200).Value = userName;
string password = txtRegisterRepeatPassword.Text;
command.Parameters.Add("#Password", SqlDbType.VarChar, 200).Value = password;
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.Add("#QuestionOne", SqlDbType.VarChar, 200).Value = questionOne;
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.Add("#QuestionTwo", SqlDbType.VarChar, 200).Value = questionTwo;
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.Add("#AnswerOne", SqlDbType.VarChar, 200).Value = answerOne;
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.Add("#AnswerTwo", SqlDbType.VarChar, 200).Value = answerTwo;
command.ExecuteNonQuery();
connection1.Close();
}

"Data type mismatch in criteria expression" when trying to delete row from database

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

Categories