MySQL C# Query trouble - Updating table - c#

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())
{
//
}

Related

The commandText property is not properly initialized

I'm trying to implement data into 2 (later on 3) tables simultaneously using a C# console application. I want to implement into table 'user' a firstname, lastname and userID, user ID will be auto incremented.
That same userID should also be implemented into table 'profile' along with a porilfeID (once again, done autoamtically by auto increment) and a profileName.
But somewhere it throws the error of commandtext not properly initialized and I cant figure out anymore what I am doing wrong.
class SQLCreate
{
public void create(int entries)
{
string ConnectionString = "server=localhost;uid=root;pwd=;database=databaseassignment;";
MySqlConnection conn;
MySqlCommand cmd;
MySqlDataAdapter adapter;
conn = new MySqlConnection();
int entryValue = entries;
conn.ConnectionString = ConnectionString;
try
{
Stopwatch stopw = new Stopwatch();
stopw.Start();
conn.Open();
cmd = new MySqlCommand();
adapter = new MySqlDataAdapter();
cmd.Connection = conn;
for (int i = 0; i < entryValue; i++)
{
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO user (firstName, lastName) VALUES (#firstName, #lastName)", conn);
//MySqlCommand cmd1 = new MySqlCommand("INSERT INTO user (firstName, lastName) VALUES (#firstName, #lastName)", conn);
cmd1.Parameters.AddWithValue("#firstName", "John");
cmd1.Parameters.AddWithValue("#lastName", "Doe");
cmd1.CommandType = CommandType.Text;
int userId = Convert.ToInt32(cmd1.ExecuteScalar());
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO profile (userId, profileName) VALUES (#userId, #profileName)", conn);
cmd2.Parameters.AddWithValue("#userId", userId);
cmd2.Parameters.AddWithValue("#profileName", "John Doe");
cmd2.CommandType = CommandType.Text;
cmd2.ExecuteNonQuery();
string firstName = Faker.Name.First();
string lastName = Faker.Name.Last();
string profileName = Faker.Name.First();
cmd.Parameters.Add("#firstName", MySqlDbType.String);
cmd.Parameters["#firstName"].Value = firstName;
cmd.Parameters.Add("#lastName", MySqlDbType.String);
cmd.Parameters["#lastName"].Value = lastName;
cmd.Parameters.Add("#profileName", MySqlDbType.String);
cmd.Parameters["#profileName"].Value = profileName;
cmd.ExecuteNonQuery();
}
conn.Close();
stopw.Stop();
Console.WriteLine(" Time elapsed: {0} ", stopw.Elapsed);
} catch (MySql.Data.MySqlClient.MySqlException ex) {
Console.WriteLine(ex.Message);
}
}
}
}
You create cmd = new MySqlCommand(); but never set its .CommandText property. Calling cmd.ExecuteNonQuery(); will fail because there's no CommandText to execute.
Either set cmd.CommandText or change the constructor to cmd = new MySqlCommand("text here", conn);.

System.Data.SqlClient.SqlException: 'Incorrect syntax near '('.'

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;
}

Error in ado.net crud operations

I want to update details. I have code in a data access class. But after executing ExecuteScalar(), it goes to the catch block and shows an exception as null.
Program :
public bool UpdateData(Customer objcust) // passing model class object because it contains all customer properties.
{
SqlConnection con = null;
// string result = "";
//int rows = 0;
try
{
string connectionString = #"server=(local)\SQLExpress;database=CustDemo;integrated Security=SSPI;";
con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Customer SET Name = #Name , Address = #Address, Gender =#Gender , City=#City WHERE Customer.CustomerID = #CustomerID",con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", objcust.Name);
cmd.Parameters.AddWithValue("#Gender", objcust.Gender);
cmd.Parameters.AddWithValue("#Address", objcust.Address);
cmd.Parameters.AddWithValue("#City", objcust.City);
con.Open();
cmd.ExecuteScalar();
return true;
}
catch(Exception ex)
{
return false;
}
}
Instead of cmd.ExecuteScalar(); Try to use
cmd.ExecuteNonQuery ();
ExecuteNonQuery is used specifically executing UPDATE, INSERT, or DELETE statements.

OleDb connection to an Access database

I've been trying to write to a database and save to the file but I cant get it to work, can't tell why either.
The error I get is:
Exception thrown: 'System.Data.OleDb.OleDbException' in System.Data.dll
Additional information:
Could not find installable ISAM.
Here's the Code I'm running, any help/advice would be greatly appreciated
private void BtnSubmit_Click(object sender, EventArgs e)
{
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =| DataDirectory |\\HoliPlanData.accdb; Trusted_Connection = True;";
String PayrollNo = TxtPayroll.Text;
String FirstName = TxtFirstName.Text;
String LastName = TxtLastName.Text;
String AnnualHolidayEntitlemet = TxtAHE.Text;
String DaysTakenToDate = TxtDTTD.Text;
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate");
Query.Connection = Conn;
Conn.Open(); //THIS IS WHERE THE ERROR OCCURS IN CODEPROSSESS
if (Conn.State == ConnectionState.Open)
{
Query.Parameters.Add("#PayrollNo", OleDbType.VarChar).Value = PayrollNo;
Query.Parameters.Add("#FirstName", OleDbType.VarChar).Value = FirstName;
Query.Parameters.Add("#LastName", OleDbType.VarChar).Value = LastName;
Query.Parameters.Add("#AnnualHolidayEntitlement", OleDbType.VarChar).Value = AnnualHolidayEntitlemet;
Query.Parameters.Add("#DaysTakenToDate", OleDbType.VarChar).Value = DaysTakenToDate;
try
{
Query.ExecuteNonQuery();
MessageBox.Show("Data Added Successfully");
Conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
Conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
Two issues:
Your connection string has an extra semicolon as you pointed out in comments above
Your INSERT query is missing the last parenthesis )
Compare these lines:
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate");
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate)");
Install AccessDatabaseEngine and try again.
Change the connection string as below.
Conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\\HoliPlanData.accdb;Trusted_Connection = True;";

Connect to SQL Server in C#

I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}

Categories

Resources