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.
Related
I have the following code that is comparing a hash value and username to the corresponding hash value and username in a local database (App_Users3)
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT Username, Hash FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
// savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value = savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show(" Query successful.. something matched.. ");
// change page.. load a profile?
}
It doesn't throw any errors but I don't understand why the messagebox isn't showing up.
ExecuteNonQuery returns the rows affected by modifying data statements (insert, update, delete). You should use ExecuteScalar for such select statements, and for example return the user's ID value. If you want to return more than one value (either multiple rows or multiple columns), you should use ExecuteReader.
Here is your code modified to return UserID of the matched user.
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT UserId FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
//savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value= savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteScalar() != null) {
MessageBox.Show(" Query successful..something matched.. ");
//change page.. load a profile?
}
}
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();
}
Can Anybody tell me Where is the error, I am getting Error at cmd.ExecuteNonquery() i.e Incorrect syntax near 'varchar'. Incorrect syntax near 'Type'.
string CS = ConfigurationManager.ConnectionStrings["RelayTestMachine.Properties.Settings.RelayTestConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TestValue (Relay Type,Applied Voltage) VALUES(#Relay Type,#Applied Voltage)",con);
cmd.Parameters.Add("#Relay Type", SqlDbType.VarChar).Value = tbRelayType.Text;
if (rbtn100.Checked == true)
{
cmd.Parameters.Add("#Applied Voltage", SqlDbType.VarChar).Value = rbtn100.Text;
}
if (rbtn75.Checked == true)
{
cmd.Parameters.Add("#Applied Voltage", SqlDbType.VarChar).Value = rbtn75.Text;
}
con.Open();
cmd.ExecuteNonQuery();
}
Try to use this insert statement
INSERT INTO TestValue ([Relay Type],[Applied Voltage]) VALUES(#RelayType,#AppliedVoltage)
i.e, you need to remove the spaces from variable names and put the column names inside the []
Remove white spaces from variable name and add [] to column names.
White Spaces are not allowed in variable name and if column names
consist of spaces in between then they must be enclosed with [] or
""
INSERT INTO TestValue ([Relay Type],[Applied Voltage]) VALUES(#RelayType,#AppliedVoltage)"
the whole goes like this
string CS = ConfigurationManager.ConnectionStrings["RelayTestMachine.Properties.Settings.RelayTestConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TestValue ([Relay Type],[Applied Voltage]) VALUES(#RelayType,#AppliedVoltage)",con);
cmd.Parameters.Add("#RelayType", SqlDbType.VarChar).Value = tbRelayType.Text;
if (rbtn100.Checked == true)
{
cmd.Parameters.Add("#AppliedVoltage", SqlDbType.VarChar).Value = rbtn100.Text;
}
if (rbtn75.Checked == true)
{
cmd.Parameters.Add("#AppliedVoltage", SqlDbType.VarChar).Value = rbtn75.Text;
}
con.Open();
cmd.ExecuteNonQuery();
}
I try to get the id of the last inserted t ouristin the table as I put Selct SCOPE_IDENTITY; after the insert query.
The problem is that when I try to show the id of the inserted tourist in the label - just nothing happens. (only the insert query is executed);
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += "VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir);Select SCOPE_IDENTITY()";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir",tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir",tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir",tx888_2.Text);
int added = 0;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
if (added > 0)
{
lblproba.Text+=added.ToString();
}
}
catch (Exception ex)
{
//lblResult.Text = ex.Message;
}
I have a window in WPF. When I user enter name, I want to insert it to database and get USERID.
private void button1_Click(object sender, RoutedEventArgs e)
{
OleDbDataReader rd;
string name=comboBox1.Text;
OleDbConnection conn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CellBiology.mdb;Persist Security Info=
True");
string sql = "select * from UserInformation where UserName='" + name+ "'";
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
rd = cmd.ExecuteReader();
if (rd.Read())
{
string id = rd["UserID"].ToString();
MessageBox.Show(id);
}
else
{
string sql2 = "insert into UserInformation(UserName) values ('" + ad+ "')";
OleDbCommand ne = new OleDbCommand(sql2, conn);
ne.ExecuteNonQuery();
**the problem is here.**
}
I believe you are never initializing the variable ad you are using in the following SQL:
string sql2 = "insert into UserInformation(UserName) values ('" + ad+ "')";
Which is a problem.