I am having trouble inserting into my database with c# - 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();
}

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.

Checking if a user exists, and stopping a database insert (access database)

I just don't know how to check if the users exists in the database and stop it from inserting a new row to the db (which will cause an error as I set the user to be a primary key)
protected void Button1_Click1(object sender, EventArgs e)
{
{
OleDbConnection myconnection = new OleDbConnection();
myconnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Event.mdb";
myconnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
myCommand.CommandType = CommandType.Text;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
myCommand.CommandText = query;
try
{
int amountOfUsers = (int)myCommand.ExecuteScalar();
if (amountOfUsers < 1)
{
String myQuery = "insert into users (uname,upassword,email,type) Values ('" + UserName.Text + "','" + Password.Text + "' ,'" + Email.Text + "',' user');";
myCommand.CommandText = myQuery;
myCommand.ExecuteNonQuery();
Label1.Text = "user registered";
}
else
{
Label1.Text = "user already exists";
UserName.Text = "";
Email.Text = "";
}
}
finally
{
myconnection.Close();
}
}
}
correct your query:
query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'" ,UserName.Text );
Your question isn't clear at all but I can suggest a few things..
First of all, I think you forget to use your uname as a second parameter in your:
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
line. You used {0} but never point any value to this parameter. (I assume you don't have a username called {0}) Like;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'", UserName.Text);
As a second, please always use parameterized queries. This kind of string concatenations are open for SQL Injection attakcs.
Like;
String myQuery = "insert into users (uname,upassword,email,type) Values (#uname, #upassword, #email, #type)";
OleDbCommand myCommand = new OleDbCommand(myQuery);
myCommand.Parameters.AddWithValue("#uname", UserName.Text);
myCommand.Parameters.AddWithValue("#upassword", Password.Text);
myCommand.Parameters.AddWithValue("#uname", Email.Text);
myCommand.Parameters.AddWithValue("#uname", "user");
i want to check if the username in UserName.Text is availble in the
data base or no and if it does i want to stop from inserting new data
Than you should use SELECT first to check your username is exist in your database or not like;
string query = string.Format("SELECT * FROM users WHERE uname = '{0}'", UserName.Text);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
SqlDataReader reader = myCommand.ExecuteReader();
if(reader.HasRows)
{
//Your username exist in your database
}
else
{
//Doesn't exist
}
you have missing the parameter uname , you have pass the text of UserName textbox to uname
for eg
"SELECT COUNT(*) FROM users WHERE uname='" + UserName.Text +"'

how to use executereader to read one value

I want to read an int value from my table. but I faced with error
this is my code. please help me to edit my code.
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
SqlDataReader rdr = cmd.ExecuteReader();
// loop over all rows returned by SqlDataReader
while(rdr.Read())
{
RemainedChargeLbl.Text=rdr.GetString(0);
}
To read one value you don't need reader. Use SqlCommand.ExecuteScalar Method which executes query and returns first column of the first row in result set returned by query:
int value = (int)cmd.ExecuteScalcar();
BTW it's better to create command object with sqlc.CreateCommand() - it creates appropriate command and automatically assigns connection to it.
You are not assigning connection object sqlc to the SqlCommand.
Add this:
cmd.Connection=sqlc;
Complete Solution:
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection=sqlc;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
RemainedChargeLbl.Text =((int) cmd.ExecuteScalar()).ToString();
Use this code:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username);
cmd.Parameters.AddWithValue("#id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}

return student information - SQL/C# assignment

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();
}

C# SqlDataReader = null?

String sqlCheckPass =
"Select * from Login where Username like #Username and Password like #Password";
SqlCommand SqlCom = new SqlCommand(sqlCheckPass, myConnection);
SqlCom.Parameters.Add(new SqlParameter("#Username", sUserName));
SqlCom.Parameters.Add(new SqlParameter("#Password", sPassword));
myConnection.Open();
SqlDataReader myreader;
myreader = SqlCom.ExecuteReader();
int id = -1;
ErrorBox.InnerHtml = "Username:" + sUserName + ":" + sPassword + ":<br/>";
while (myreader.HasRows)
{
id = (int)myreader["id"];
String sUser = (String)myreader["Username"];
String sPass = (String)myreader["Password"];
ErrorBox.InnerHtml += "UserId is <b>" + id + "</b> " + sUser + ":" + sPass + ":<br >";
Session["LoginID"] = id;
Server.Transfer(ReturnPage);
}
if (id == -1)
{
ErrorBox.InnerHtml = "Incorrect Password";
}
myConnection.Close();
catch (Exception err)
{
ErrorBox.InnerHtml = "Error Getting Option ID" + err.Message;
}
I added a breakpoint at myreader = SqlCom.ExecuteReader(); and it keeps returning myreader as null and HasRows = False, but it does have rows. So, it keeps validating my login as incorrect since id = -1,
Help?
You didn't connect your reader to your SQL connection/command?
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
The problem might be the LIKE in your query with the SqlParameters. Try
String sqlCheckPass =
"Select * from Login where Username like '%' + #Username + '%' and Password like '%' + #Password + '%'";
Bryan Denny's answer above is correct, however, I'll enclose all of the code inside using statements as shown below:
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand SqlCom = dataConnection.CreateCommand())
{
SqlCom.CommandText = "Select * from Login where Username like #Username and Password like #Password";
SqlCom.Parameters.Add(new SqlParameter("#Username", sUserName));
SqlCom.Parameters.Add(new SqlParameter("#Password", sPassword));
dataConnection.Open();
SqlDataReader myreader;
myreader = SqlCom.ExecuteReader();
dataConnection.Close();
}
}
I didn't add all of your code to this snippet, I figured you get the idea.
Also, you could try modifying the select statement to return a count of records since this is all you need anyways, a number:
SELECT COUNT(*) FROM Login WHERE Username like #Username AND Password like #Password
Good luck!

Categories