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();
}
Related
I am facing this error while i was trying to convert the session object type to int, I need to use that value in another query which is of datatype int.
SqlConnection sqlConnection1 = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=DESKTOP-59SGH72\\SQLEXPRESS;Trusted_Connection=True;Database=sport");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "select user_id from users where user_name='" + Session["usern"] + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
Session["userid"] = reader;
var uid = Convert.ToInt16(Session["userid"]);
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Please help me with this error !!
first of all your code is terrible -- it is totally going to get hacked by an injection attack. You should be using a parameterized query.
as to your question, something like this would work but you really should be doing lots of error checking and sanity checks:
reader = cmd.ExecuteReader();
reader.Read();
Session["userid"] = reader[0];
You probably should have looked at the documentation which has some nice examples
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
Just want to use windows forms interface to insert data into the database.
I think the code is right, but it is giving me an error saying "Incorrect syntax near the keyword 'User'."
image with tables names here
try
{
string cmdString = #"insert into User (userName, userEmail, userBalance, userTickets) VALUES (#userName, #userEmail, #userBalance, #userTickets)" +
"insert into Account (accountName, accountPassword) VALUES (#accountName, #accountPassword)";
// Connection
SqlConnection con = new SqlConnection("i dont know if is safe to show the con string...but i know its right");
SqlCommand cmd = new SqlCommand(cmdString, con);
con.Open();
cmd.Parameters.Add("#userName", SqlDbType.NVarChar).Value = txtUserName.Text;
cmd.Parameters.AddWithValue("#userEmail", SqlDbType.NVarChar).Value = txtemail.Text;
cmd.Parameters.AddWithValue("#userBalance", SqlDbType.Money).Value = 100;
cmd.Parameters.AddWithValue("#userTickets", SqlDbType.Int).Value = 3;
//cmd.Parameters.AddWithValue("#accountID", null);
cmd.Parameters.AddWithValue("#accountName", SqlDbType.NVarChar).Value = txtUserName.Text;
cmd.Parameters.AddWithValue("#accountPassword", SqlDbType.NVarChar).Value = txtPassword.Text;
// Execute command
cmd.ExecuteNonQuery();
con.Close();
//MessageBox.Show("Data saved!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Can somebody give me a hand?
User is a reserved word.
You need to enclose it in square brackets:
string cmdString = #"insert into [User] (userName, userEmail, userBalance, userTickets) VALUES (#userName, #userEmail, #userBalance, #userTickets)" +
"insert into Account (accountName, accountPassword) VALUES (#accountName, #accountPassword)";
Doing this will tell SQL to treat it as a table name and not the reserved word.
I have a problem with a UPDATE query.
The UPDATE doesn't update the database at all...
It feels like the command.ExecuteNonQuery() doesn't happen.
Here is the code:
-- The Connection was opened before --
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
command.CommandText = "UPDATE users SET user_name=#userName, pass_word=#pass, Uname=#Uname WHERE id=#id";
command.Parameters.AddWithValue("#id", theId);
command.Parameters.AddWithValue("#userName", userName);
command.Parameters.AddWithValue("#pass", pass);
command.Parameters.AddWithValue("#Uname", Uname);
command.ExecuteNonQuery();
Response.Redirect("~/profile.cshtml");
Thanks for any help
Etay
I really need help this time. I search everywhere, tried numerous solutions. but i can't seem to solve my problem. Now i'm going to ask, please help. I have been having this problem for a week now.
ExecuteSQL("select * from account_database where idnum= #idnum and password= #pass")
'Dim idnum As New SqlParameter("#idnum", SqlDbType.VarChar)
'Dim pass As New SqlParameter("#pass", SqlDbType.VarChar, -1)
'idnum.Value = idnumtxt.Text
'pass.Value = output
'cmd.Parameters.Add(idnum)
'cmd.Parameters.Add(pass)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
those commented out lines are the codes which i have tried, also there are codes which i implemented that also failed.
The error message concludes as "Must declare scalar variable #idnum"
i really need help please. Please shine some light.
This is the code what the function executeSQL contains :
Public Shared Sub ExecuteSQL(ByVal strSQL As String)
Try
If connection.State = 1 Then ' check connection if open
connection.Close()
End If
' connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
connection.Open()
Dim rowAffected As Integer = 0
'cmd = New SqlCommand(strSQL, connection) 'buiding the sql command with the use of strSQL (sql statement) and connection (database connection)
cmd = New SqlCommand(strSQL, connection)
DARec = New SqlDataAdapter(strSQL, connection) 'buiding the adapter
cb = New SqlCommandBuilder(DARec)
rowAffected = cmd.ExecuteNonQuery() 'executing of sql statement
successID = 1
connection.Close()
Catch ex As Exception
successID = 0
MsgBox(ex.Message)
End Try
End Sub
Thanks and please help.
Problem is simply you're doing this in the wrong order. You're attempting to execute your SQL statement before defining the parameters. You don't need ExecuteSQL() until you've defined your parameters. It likely breaks on the following line in ExecuteSQL()
' See how many rows the query will impact
' Since #idnum and #pass are not defined until the
' ExecuteSQL() sub is finished, this line breaks.
rowAffected = cmd.ExecuteNonQuery()
You need to build your SqlCommand() to first include the select statement, and then use AddWithValue() on the parameters you've defined in the string. Defining the datatypes is also unnecessary because your database already knows, and form validation should handle input.
' Define your connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
' Setup your SQL Command.
cmd = New SqlCommand("select * from account_database where idnum = #idnum and password = #pass", connection)
' Define the parameters you've created
cmd.Parameters.AddWithValue("#idnum", idnumtxt.Text)
cmd.Parameters.AddWithValue("#pass", output)
' Now execute your statement
connection.open()
cmd.ExecuteNonQuery()
connection.close()
And here is a better version of the above code, since you understand the order of events now. This ensures that in the event of exception the connection is closed.
strConn = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
strSQL = "select * from account_database where idnum = #idnum and password = #pass"
Using connection As New SqlConnection(strConn), cmd As SqlCommand(strSQL, connection)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
connection.Open()
cmd.ExecuteNonQuery()
End Using
Try this:
cmd.Parameters.AddWithValue("idnum", idnumtxt.Text)
Reference:
SqlParameterCollection.AddWithValue # MSDN.
It should just be a case of the following to add an input param
cmd.Parameters.Add("#idnum", idnumtxt.Text)
Except you'll need cmd.parameters.add() before the executesql as you're currently defining your params after executesql has ran.
I'm getting an error while trying to insert a date into database, here is the insert command:
cmd.CommandText = "INSERT INTO Customer([date1])VALUES(Convert.ToDateTime(date1.Text))
the error is :
String was not recognized as a valid datetime.
What you have here is a string.
Convert.ToDateTime(date1.Text)
will never compile to what you need. It will be send as such in the DB. Use a parameterized command and pass the result of this in a parameter.
For instance:
string sqlstring = "INSERT INTO Customer([date1])VALUES(#Date)";
SqlCommand cmd = new SqlCommand(sqlstring, conn);
SqlParameter par = new SqlParameter("#Date", Convert.ToDateTime(date1.Text));
cmd.Parameters.Add(par);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();