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 ) ... ?
Related
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;
}
Okay so from my previous question this is one iteration of how I am pulling data from the SQL Server and then inserting that same data into CtreeACE where the table is already setup for the values to be stored in there. When I run the code I get
Things I have tried:
rewriting the method
Refining how the items are stored after being pulled
Making sure the names matched the correct call names
Debugged my code multiple times and still can't wrap my head around it
Here is the code
class Program
{
static CtreeSqlConnection _conn;
static CtreeSqlCommand cmd;
static CtreeSqlDataReader reader;
static void Main(string[] args)
{ //Creating the connection to the SQL server
SqlConnection conn = new SqlConnection("Server=bldg-db-pri.MDHUN.us.ups.com\\p001;Database=D90;Integrated Security=true");
//Open the connection
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP(100) l.tracingID, u.Sch_dt, p.address, p.city, p.state, u.zip, m.Time " +
"FROM D490AD0.dbo.TUWUOW1 u WITH (nolock) " +
"INNER JOIN D90.dbo.TUW p WITH (nolock) ON p.UOW = u.UOW " +
"INNER JOIN D90.dbo.TUW2 l WITH (nolock) ON l.UOW = u.UOW " +
"CROSS JOIN D90.dbo.tTN m " +
"WHERE " +
"u.Sch_dt = '2018-07-23' ", conn); //query that intializes after the connection is opened
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"{reader["tracingID"]} |" +
$"{reader["Time"]} |" +
$"{reader["state"]} |" +
$"{reader["address1"]} |" +
$"{reader["address1"]} |" +
$"{reader["address3"]} |" +
$"{reader["city"]} |" +
$"{reader["zip"]} |" +
$"{reader["Sch_dt"]}"
);
try
{
DataInsertion($"{reader["tracingID"]} " ,
$"{reader["Time"]} " ,
$"{reader["state"]} " ,
$"{reader["address1"]} ",
$"{reader["address1"]} " ,
$"{reader["address3"]} ",
$"{reader["city"]} " ,
$"{reader["zip"]} " ,
$"{reader["Sch_dt"]}"
);
}
catch (CtreeSqlException e)
{
Console.WriteLine(e + " couldn't run method");
}
}
}
reader.Close();
conn.Close();
if(Debugger.IsAttached)
{
Console.ReadLine();
}
}
public static void DataInsertion(string tracingID, string Time, string state, string address1, string address2, string address3, string city, string zip, string Sch_dt)
{
_conn = new CtreeSqlConnection();
_conn.ConnectionString = "UID=ADMIN;PWD=ADMIN;Database=AttributeDB;Server=localhost;Service=6597;";
_conn.Open();
if (_conn == null)
{
Console.WriteLine("Could not connect to Ctree");
}
try
{
cmd.CommandText = "INSERT INTO tbl6(tracingID, Time, state, address, city, zipcode, dates) VALUES(tracingID, Time, state ,address, city, zip, Sch_dt)";
cmd.Parameters.Clear();
cmd.Parameters.Add(new CtreeSqlParameter(tracingID));
cmd.Parameters.Add(new CtreeSqlParameter(Time));
cmd.Parameters.Add(new CtreeSqlParameter(state));
cmd.Parameters.Add(new CtreeSqlParameter(address));
cmd.Parameters.Add(new CtreeSqlParameter(city));
cmd.Parameters.Add(new CtreeSqlParameter(zip));
cmd.Parameters.Add(new CtreeSqlParameter(Sch_dt));
cmd.ExecuteNonQuery();
}
catch (CtreeSqlException ctsqlEx)
{
Console.WriteLine("Something went wrong with the command script");
}
}
}
This is where the method inserts the pulled data into the Ctreedatabase
CtreeSqlCommand cmd = new CtreeSqlCommand("INSERT INTO tbl6(tracingID, Time, state, address, city, zipcode, dates) VALUES(tracingID, Time, state ,address, city, zip, Sch_dt)", _conn);
cmd.Parameters.Clear();
cmd.Parameters.Add(new CtreeSqlParameter(tracingID));
cmd.Parameters.Add(new CtreeSqlParameter(Time));
cmd.Parameters.Add(new CtreeSqlParameter(state));
cmd.Parameters.Add(new CtreeSqlParameter(address));
cmd.Parameters.Add(new CtreeSqlParameter(city));
cmd.Parameters.Add(new CtreeSqlParameter(zip));
cmd.Parameters.Add(new CtreeSqlParameter(Sch_dt));
cmd.ExecuteNonQuery();
}
I assume the values aren't being passed in?
Everytime I run the program none of the values show up within the ctree database
Exceptions after code runs
Ctree.Data.SqlClient.CtreeSqlException (0x7FFFB1DD): Syntax error ---> Ctree.SqlClient.Common.FcSqlException: Syntax error
at Ctree.SqlClient.FcSqlXApi.SQLExec(FcStatement stmt, Int32 InStatementType, FcSqlDA ida, FcSqlDA oda, FcSqlCA sqlca)
at Ctree.SqlClient.FcSqlXApi.Prepare(FcStatement stmt, FcSqlDA input_sqlda, FcSqlDA output_sqlda, Int32 fetchSize)
at Ctree.SqlClient.FcConnection.Prepare(FcStatement statement, FcSqlDA inputDA, FcSqlDA outputDA, Int32 fetchSize)
at Ctree.SqlClient.FcPreparedStatement..ctor(FcConnection connexion, String sql, Int32 fetchSize, Int32 timeout)
at Ctree.Data.SqlClient.CtreeSqlCommand.InternalPrepare(Boolean resultSet)
at Ctree.Data.SqlClient.CtreeSqlCommand.ExecuteNonQuery()
at Ctree.Data.SqlClient.CtreeSqlCommand.ExecuteNonQuery()
Could you try replacing:
CtreeSqlCommand cmd = new CtreeSqlCommand(#"INSERT INTO tbl6(tracingID, Time, state, address, city, zipcode, dates)
VALUES(tracingID, Time, state ,address, city, zip, Sch_dt)", _conn);
cmd.Parameters.Clear();
cmd.Parameters.Add(new CtreeSqlParameter(tracingID));
With something like this:
CtreeSqlCommand cmd = new CtreeSqlCommand(#"INSERT INTO tbl6(tracingID, Time, state, address, city, zipcode, dates)
VALUES(#tracingID, #Time, #state, #address, #city, #zip, #Sch_dt)", _conn);
cmd.Parameters.Clear();
cmd.Parameters.Add(new CtreeSqlParameter("#tracingID", tracingId));
etc. i.e. do the same for all the other parameters.
Note I split your command onto two lines, just to make it more obvious that I added an "#" before each parameter value, so this was just for readability.
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'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())
{
//
}
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);
}
}