My INSERT Statement is giving me each INSERT twice, like this:
http://i.imgur.com/cMRiXfk.png
public static void insertStudent(int personId, string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode, string majorField, int gradePointAverage, int Person_personId)
{
try
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personId, firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#personId, #firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)";
cmd.Prepare();
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("#personId", personId);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
cmd.ExecuteNonQuery();
string myInsertSQLStudent = "INSERT INTO student(majorField, gradePointAverage, person_personId) VALUES (#majorField, #gradePointAverage, #person_personId)";
cmd.Prepare();
cmd.CommandText = myInsertSQLStudent;
cmd.Parameters.AddWithValue("#person_personId", Person_personId);
cmd.Parameters.AddWithValue("#majorField", majorField);
cmd.Parameters.AddWithValue("#gradePointAverage", gradePointAverage);
prevID(conn, cmd);
}
catch
{
MessageBox.Show("Invalid User Name or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I have two INSERT statements, because some text boxes have to go to one table and some have to go to another.
EDIT:
This is the button that calls it:
private void btnInsertStudentNumberAdmin_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(int.Parse(txtPersonIDStudent.Text), txtFirstNameStudent.Text, txtLastNameStudent.Text, txtDOBStudent.Text, int.Parse(txtPhoneNumberStudent.Text), txtAddressStudent.Text, int.Parse(txtPostCodeStudent.Text), txtMajorFieldStudent.Text, int.Parse(txtGpaStudent.Text), int.Parse(txtPerson_PersonIdStudent.Text));
}
SORRY EDIT:
So I just called my person table in mySql and the INSERT isnt being repeated, my SELECT/data grid is adding the set on top of the old one
try to create a new command and not use the same one for the second insert:
public static void insertStudent(int personId, string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode, string majorField, int gradePointAverage, int Person_personId)
{
try
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personId, firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#personId, #firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)";
cmd.Prepare();
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("#personId", personId);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
cmd.ExecuteNonQuery();
MySqlCommand cmd2 = new MySqlCommand();
cmd2.Connection = conn;
string myInsertSQLStudent = "INSERT INTO student(majorField, gradePointAverage, person_personId) VALUES (#majorField, #gradePointAverage, #person_personId)";
cmd2.Prepare();
cmd2.CommandText = myInsertSQLStudent;
cmd2.Parameters.AddWithValue("#person_personId", Person_personId);
cmd2.Parameters.AddWithValue("#majorField", majorField);
cmd2.Parameters.AddWithValue("#gradePointAverage", gradePointAverage);
prevID(conn, cmd2);
}
catch
{
MessageBox.Show("Invalid User Name or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Related
This question already has answers here:
The parameterized query ..... expects the parameter '#units', which was not supplied
(5 answers)
Closed 2 years ago.
Are there any gurus out there that might be able to help me figure this out? I keep throwing this exception in C#, but everything that I can see seems to be correct. Here is the code
public bool Insert(loginBLL u)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
String sql = "INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username) VALUES (#firstname, #lastname, #phone, #email, #address, #city, #state, #zipcode, #password, #username)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#firstname", u.firstname);
cmd.Parameters.AddWithValue("#lastname", u.lastname);
cmd.Parameters.AddWithValue("#phone", u.phone);
cmd.Parameters.AddWithValue("#email", u.email);
cmd.Parameters.AddWithValue("#address", u.address);
cmd.Parameters.AddWithValue("#city", u.city);
cmd.Parameters.AddWithValue("#state", u.state);
cmd.Parameters.AddWithValue("#zipcode", u.zipcode);
cmd.Parameters.AddWithValue("#password", u.password);
cmd.Parameters.AddWithValue("#username", u.username);
conn.Open();
int rows = cmd.ExecuteNonQuery();
I suspect your problem is due to passing (object)null instead of DBNull.Value for null parameters.
These days, I'd avoid all that parameter boilerplate by writing an extension method to bind parameters from a FormattableString.
public static SqlCommand GetCommandInterpolated(this SqlConnection conn, FormattableString sql)
{
var cmd = conn.CreateCommand();
var replacements = new string[sql.ArgumentCount];
var args = sql.GetArguments();
for (int i = 0; i < sql.ArgumentCount; i++)
{
var p = cmd.CreateParameter();
cmd.Parameters.Add(p);
p.ParameterName = replacements[i] = $"#p_{i}";
p.Value = args[i] ?? DBNull.Value;
}
cmd.CommandText = string.Format(sql.Format, replacements);
return cmd;
}
var cmd = conn.GetCommandInterpolated(
$#"INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username)
VALUES ({u.firstname}, {u.lastname}, {u.phone}, {u.email}, {u.address}, {u.city}, {u.state}, {u.zipcode}, {u.password}, {u.username}"
);
I am trying to insert data into my database. I can't find any reason why my affectedResults are 0 and it keeps crashing out giving me a big squiggly on my cmd.ExecuteNonQuery(), it says there is a 'Incorrect syntax near '('.' so I have carefully analyzed my sql statement for the past hour and i'm not too sure where the problem is.
private int SendData(string sqlStatement)
{
SqlConnection conn = new SqlConnection(Properties.Settings.Default.cnnString);
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
int AffectedRecords = 0;
using (conn)
{
conn.Open();
AffectedRecords = cmd.ExecuteNonQuery();
conn.Close();
}
return AffectedRecords;
}
private void InsertData()
{
string sql = string.Format("INSERT INTO Participant (LastName, FirstName, " + ("Country, Gender, IACMember, Rank, SponsorId" +
"VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\','{4}',{5}, {6})"),
txtLastName.Text, txtFirstName.Text, cboCountry.SelectedItem, Gender(gender),
(chkMember.Checked), ((txtRank.Text == string.Empty) ? "Null" : txtRank.Text),
((cboSponsor.Text == "No Sponsor") ? "Null" : cboSponsor.SelectedValue));
SendData(sql);
}
Why don't you insert data the simple way? Also you are exposing yourself to SQL INJECTIONS. Here is the Method
private int InsertData()
{
int AffectedRecords = 0;
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.cnnString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Participant (LastName, FirstName, Country, Gender, IACMember, Rank, SponsorId) VALUES (#LastName, #FirstName, #Country, #Gender, #IACMember, #Rank, #SponsorId)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cboCountry.SelectedItem);
//Your Remaining Fields
AffectedRecords = cmd.ExecuteNonQuery();
}
}
return AffectedRecords;
}
I have the following INSERT:
public static void insertStudent(int personId, string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode, string majorField, int gradePointAverage)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "INSERT INTO person (personId, firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#personId, #firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("#personId", personId);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
cmd.ExecuteNonQuery();
long id = (long)cmd.LastInsertedId;
sql = "INSERT INTO student (Person_PersonId, majorField , gradePointAverage) VALUES (" + id + ",#majorField, #gradePointAverage";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#majorField", majorField);
cmd.Parameters.AddWithValue("#gradePointAverage", gradePointAverage);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("New student record created created.");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
executed by this button:
private void btnInsertStudentNumberAdmin_Click(object sender, EventArgs e)
{
StudentHelperClass.insertStudent(int.Parse(txtPersonIDStudent.Text), txtFirstNameStudent.Text, txtLastNameStudent.Text, txtDOBStudent.Text, int.Parse(txtPhoneNumberStudent.Text), txtAddressStudent.Text, int.Parse(txtPostCodeStudent.Text), txtMajorFieldStudent.Text, int.Parse(txtGpaStudent.Text));
}
But on the click, I get a message box saying you have an error in your SQL syntax; check the manual that corresponds to your mySql server version for the right version for the right syntax to use near " at line 1 and then my entries for the person table get inserted, but the ones for student do not.
I have made sure that all the ints are int's and all the strings are strings. I'm not sure what the problem is.
sql = "INSERT INTO student (
Person_PersonId,
majorField,
gradePointAverage
) VALUES (" + id + ",
#majorField,
#gradePointAverage";
is missing a close parentheses. It should be:
sql = "INSERT INTO student (
Person_PersonId,
majorField,
gradePointAverage
) VALUES (" + id + ",
#majorField,
#gradePointAverage
)";
sql = "INSERT INTO student (Person_PersonId, majorField , gradePointAverage) VALUES (" + id + ",#majorField, #gradePointAverage)";
missing the ending ) ... ?
I'am having trouble with this function I'm creating to Update my database. The Update faculty member seems to work perfectly while the Updating of the person tables does not . I'm presuming that the MySQL Query isn't correct for updating the person table.
Additional INFO: My code is hooked to an GUI mock as of right now for testing purposes . the Update string with #Id.. its just to select which ID I wish to change..
public static void Update(string update,string fName, string lName, string DOB, string postCode, string address, string phoneNumber,
bool isTenured, string qualifications, string previousEmployment)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "UPDATE person SET firstName = #FirstName , lastName = #LastName, DOB = #DOB, phoneNumber = #PhoneNumber, address = #Address, postCode = #PostCode WHERE ID =#Id;";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("#Id", update);
cmd.Parameters.AddWithValue("#FirstName", fName);
cmd.Parameters.AddWithValue("#LastName", lName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#PhoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#PostCode", postCode);
long id = (long)cmd.LastInsertedId;
sql = "UPDATE facultymember SET isTenured = #IsTenured, qualifications = #Qualifications, previousEmployment = #PreviousEmployment WHERE Person_personID=#Id";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#IsTenured", isTenured);
cmd.Parameters.AddWithValue("#Qualifications", qualifications);
cmd.Parameters.AddWithValue("#PreviousEmployment", previousEmployment);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("Updated");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
You forget to add #Id parameter in your second sql query.
sql = "UPDATE facultymember
SET isTenured = #IsTenured, qualifications = #Qualifications, previousEmployment = #PreviousEmployment
WHERE Person_personID=#Id";
// ^^^^
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#IsTenured", isTenured);
cmd.Parameters.AddWithValue("#Qualifications", qualifications);
cmd.Parameters.AddWithValue("#PreviousEmployment", previousEmployment);
cmd.Parameters.AddWithValue("#Id", YourIdValue);
cmd.ExecuteNonQuery();
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(ConnectionString))
using(MySqlCommand cmd = conn.CreateCommand())
{
//
}
I have created a simple program to insert values into the table [regist], but I keep getting the error
Incorrect syntax near ')'
on cmd.ExecuteNonQuery();:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact, " + ") VALUES (" + " #textBox1.Text, #textBox2.Text, #textBox3.Text, #textBox4.Text, #comboBox1.Text,#comboBox2.Text,#textBox7.Text" + ")", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I am new to this and I am really confused.
As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.
Also: I would recommend to separate the click event handler from the actual code to insert the data.
So I would rewrite your code to be something like
In your web page's code-behind file (yourpage.aspx.cs)
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
InsertData(connectionString,
textBox1.Text.Trim(), -- first name
textBox2.Text.Trim(), -- last name
textBox3.Text.Trim(), -- user name
textBox4.Text.Trim(), -- password
Convert.ToInt32(comboBox1.Text), -- age
comboBox2.Text.Trim(), -- gender
textBox7.Text.Trim() ); -- contact
}
In some other code (e.g. a databaselayer.cs):
private void InsertData(string connectionString, string firstName, string lastname, string username, string password
int Age, string gender, string contact)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FirstName, #Lastname, #Username, #Password, #Age, #Gender, #Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("#Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("#Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("#Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Code like this:
is not vulnerable to SQL injection attacks
performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"
// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
// Collecting Values
string firstName="Name",
lastName="LastName",
userName="UserName",
password="123",
gender="Male",
contact="Contact";
int age=26;
// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FN, #LN, #UN, #Pass, #Age, #Gender, #Contact) ";
// instance connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// add parameters and their values
cmd.Parameters.Add("#FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
cmd.Parameters.Add("#LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
cmd.Parameters.Add("#UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
cmd.Parameters.Add("#Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#Age", System.Data.SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
cmd.Parameters.Add("#Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;
// open connection, execute command and close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}