SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (ParticipantId, LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#ParticipantId, #LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
// cmd.Parameters.AddWithValue("#ParticipantId", notnull);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender.Text);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
cmd.ExecuteNonQuery();
cnn.Close();
I keep getting the error message:
"System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#ParticipantId".' "
I have tried this multiple ways and have been trying to figure this out for a week now. I'm not understanding what is the bug in my code.
Updated version below:
SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
//cmd.Parameters.AddWithValue("#ParticipantId", );
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
int nextKey;
cmd = new SqlCommand("SELECT MAX(ParticipantId) FROM Participant", cnn);
nextKey = (int)cmd.ExecuteScalar() + 1;
// cmd.ExecuteNonQuery();
cnn.Close();
if the column ParticipantId is marked as Identity Then You Should Not Try To Manually Insert data in it , sql server will populate it depending on last used ParticipantId , therefore u should remove the column from the insert statement and remove the id parameter .
if its just a Primary Key then u will need to manually insert unique value for each row .
the error mentioned above is because of the commented line which was supposed to provide a value for ParticipantId parameter
Related
I am currently working with SQL database and my assignment is to make a registration form. I have got the registration form to work but I need to check if username have already been taken. In my code Username is in the form of Emails. The code I have works, but as it is, multiple usernames are allowed.
HEre is my code:
protected void registerUser(Object src, EventArgs e)
{
Response.Write("you have connected to your .cs page add records");
get_connection();
try
{
connection.Open();
command = new SqlCommand("INSERT INTO subscribers (FirstName, LastName, Email, Password)" +
" VALUES (#FirstName, #LastName, #Email, #Password)", connection);
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
command.ExecuteNonQuery();
//connection.Close();
}
catch(Exception err)
{
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text += "<br /><b>Record has been added</b>";
//lblInfo.Text = "<b>Server Version:</b> " + connection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + connection.State.ToString();
}
}
To check if the username had already been taken, I was thinking about using an "If Then" statement within the "try" area but am unsure what coding I would need. Any help or advice would be appreciated.
You can write something like this:
string cmdText = #"IF NOT EXISTS(SELECT 1 FROM subscribers where Email = #Email)
INSERT INTO subscribers (FirstName, LastName, Email, Password)
VALUES (#FirstName, #LastName, #Email, #Password)"
command = new SqlCommand(cmdText, connection);
......
You can try this code :
string sqlQuery = "IF NOT EXISTS (SELECT 1 FROM subscribers where Email = #Email)
BEGIN
INSERT INTO subscribers (FirstName, LastName, Email, Password) VALUES (#FirstName, #LastName, #Email, #Password)
SELECT SCOPE_IDENTITY()
END
ELSE SELECT 0"
using (command = new SqlCommand())
{
command.CommandText = sqlQuery;
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
connection.Open();
var res = (int)cmd.ExecuteScalar();
connection.Close();
}
if a result is 0 then already exists otherwise new record inserted.
I do not know why I am getting this error:
C# Code:
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=***;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO student (studentID, studentFirstName, studentLastName, studentUserName, studentPassword) VALUES (#userID, #, #FirstName, #LastName, #Username, #Password);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
It may due to me overlooking something.
Error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data
Additional information: Column count doesn't match value count at row 1
Format out your code and you'll see all the syntactic problems clearly:
string connectionString =
"datasource=localhost;port=3306;database=project;username=***;password=***;";
using (MySqlConnection connection = new MySqlConnection(connectionString)) {
connection.Open();
//DONE: keep sql readable
string sql =
#"INSERT INTO student (
studentID,
studentFirstName,
studentLastName,
studentUserName,
studentPassword)
VALUES (
#userID,
#FirstName, -- wrong # param
#LastName,
#Username,
#Password);";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql)) {
cmd.CommandType = CommandType.Text; // redundant
cmd.Connection = connection;
//DONE: separate code with new lines
// wrong parameter name
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
You are adding an additional parameter in your values clause (#userID, #,
also add the "#" before user id
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
should be
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));
I would like to update/edit my user data in Employee table in access database.
When i complete the fields that i want to change (name , last name, etc.), it gives me data updated but when i refresh the table, the data hasn't changed - been updated.
Changes i want to perform for example - Change name from Luke to Taylor, etc.
Where have i gone wrong? Where is the mistake in the code and does my code for adding users to database somehow have influence my update code?
My code for adding users is almost the same as for the update, except for query, and it works fine.
private void button2_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Update Employee set Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #ID";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User updated!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code for adding user data
private void button1_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Insert into Employee (ID, Name, LastName, UserName, Password, E_mail, Address)" + "values (#ID, #Name, #LastName, #UserName, #Password, #E_mail, #Address)";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User added!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for the replies and help
I still have no solution for this. I've tried so many things but i just don't get the right answer.
My current code
try
{
OleDbConnection myConnection = new OleDbConnection("\\DATABASE PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "UPDATE Employees SET Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #";
cmd.Parameters.AddWithValue("#ID", userID.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#LastName", lastName.Text);
cmd.Parameters.AddWithValue("#UserName", userName.Text);
cmd.Parameters.AddWithValue("#Password", pass.Text);
cmd.Parameters.AddWithValue("#E_mail", eMail.Text);
cmd.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("User successfully added.");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Its because your ID in where condition.
You are also changing/updating your ID through:
command.Parameters.AddWithValue("#ID", userID.Text);
This new ID is not found by compiler in Database since you kept where ID=#ID condition in your query.
When you just updates name and other fields then query becomes:
Update Employee set Name = 'Name', LastName = 'LastName', UserName = 'UserName', Password = 'Password', E_mail = 'E_mail', Address = 'Address' WHERE ID = ''";
Your ID might remain blank in that case.
Try the following in your update code:
command.CommandText = "UPDATE Employee SET [Name] = ?, LastName = ?, UserName = ?, [Password] = ?, [E_mail] = ?, Address = ? WHERE [ID] = ?";
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
command.Parameters.AddWithValue("#ID", userID.Text);
The parameters must be in the order in which they appear in the CommandText. This answer was suggested by: Microsoft Access UPDATE command using C# OleDbConnection and Command NOT working
The reasons for this is outlined here: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
I created some simple code, but it looks like something is working wrong with my Insert I get error about "where". What did I do wrong?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) where Login =#Login and Password=#Password and Type=#UserType ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
SQL Insert Into statement is
INSERT INTO Table_Name ( Col1, Col2, Col3)
VALUES ( Val1, Val2, Val3);
I think,
insert into dbo.UserInfo (Login, Password, UserType, ID)
where Login =#Login and Password=#Password and Type=#UserType "
try to change the code to this.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) " +
" VALUES(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
INSERT statements don't have WHERE clauses, UPDATE statements do.
You would only use a WHERE clause if there was an actual select statement.
Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
SELECT Login, Password, UserType, ID
FROM Table
where Login =#Login
and Password=#Password
and Type=#UserType
Otherwise you just use the values. Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
VALUES (#Login,#Password,#UserType, #ID)
Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Your query should probably be
"insert into dbo.UserInfo (Login, Password, UserType, ID) values (#Login, #Password, #UserType)"
I am not sure why you are using where while inserting single record to table. Below is the proper code to insert
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO UserInfo(Login, Password, UserType) VALUES(#Login,#Password,#Type)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#Login", TextBox1.Text);
cmd.Parameters.AddWithValue("#Password", TextBox2.Text + ".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
Please, follow below syntex:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
=============
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType) values(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Only check your Insert Syntax you will get the answer :
"insert into dbo.xyz(Login, Password, ID) values (#Login, #Password)"
dbo:xyz = your table name
I have 2 tables:
RESERVATION
ID, DATE, TIME, TABLE
CLIENT
ID_CLIENT, FNAME, LNAME, EMAIL, PHONE, FK_RESERVATION
I have working INSERT statement for Reservation Table-
string insertSql = "INSERT INTO Rezervacija (date,time,table) VALUES (#date,#time,#table);
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
But the problem comes with INSERT INTO Client Table Foreign Key.
Can anyone help me how to insert data into two related tables.
You'll need to modify your query to get the ID of the row that you just inserted.
string insertSql = "INSERT INTO Rezervacija (date,time,table) OUTPUT INSERTED.Id VALUES (#date,#time,#table);"
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
var **reservationId** = (int)cmd.ExecuteScalar()
string insertSql2 = "INSERT INTO CLIENT (ID_CLIENT,FNAME,LNAME,EMAIL,PHONE,FK_RESERVATION) VALUES (#clientId, #fname, #lname, #email, #phone, #reservation"
SqlCommand cmd2 = new SqlCommand(insertSql2, con);
cmd.Parameters.AddWithValue("#clientId", clientId);
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#reservation", **reservationId**);
This will allow you use the Inserted.Id in your second query as you've returned the output to a variable.