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);.
Related
I'm using C# console app to update a table with a lot of rows based on the value of two column inside MySQL.
Below is the code that I've tried to update the table.
Is it possible to execute update during dataread while loop or do I need to use other way to accomplish this?
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
Right now if I execute the programs, the data will not be updated and will show error
'There is already an open DataReader associated with this Connection which must be closed first.'
However if I close the connection, it will only execute and update the very first row which satisfy the if-else rule.
I think there must be a way for this to run in a loop without having me to run the program repeating times.
Can anyone suggest how should I fix the code for that?
U can define new connection object for that
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
MySqlConnection con1 = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con1);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
//I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
if(!rdr.read())
{
Console.WriteLine("Update query not working!!!");
}
else
{
//user_email
string usermail = Convert.ToString(user_email);
usermail = rdr[0].ToString();
Console.WriteLine("Username: {0}", usermail.ToString());
//meta_value AS 'Current Points'
string metavalue = Convert.ToString(meta_value);
metavalue = rdr[1].ToString();
Console.WriteLine("metavalue: {0}", metavalue.ToString());
//meta_value AS 'point'
string points = Convert.ToString(point);
points = rdr[2].ToString();
Console.WriteLine("point: {0}", points.ToString());
Console.ReadLine();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
Hello I have a database with drivers and a combobox which is populated with the drivers. But when I add a new driver with a button Add Driver, it's added only in Microsoft Access table, not in the combobox. And once I reload the program, the new driver is deleted from the database. I also have connected the database in Data Source and I can edit the tables only from there(if I want to edit the combobox).
This is my connection with the database
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
cmd = new OleDbCommand();
con.Open();
cmd.Connection = con;
string query = "SELECT Name FROM Drivers";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboDriver.Items.Add(reader["Name"]);
}
con.Close();
and this is my Add Driver button:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
String Id = textID.Text;
String Name = textName.Text;
String Age = textAge.Text;
String City = textCity.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Drivers (Id, Name, Age, City) Values(#Id, #Name, #Age, #City)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Id", OleDbType.VarChar).Value = Id;
cmd.Parameters.Add("#Name", OleDbType.VarChar).Value = Name;
cmd.Parameters.Add("#Age", OleDbType.VarChar).Value = Age;
cmd.Parameters.Add("#City", OleDbType.VarChar).Value = City;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("New Driver Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
Just because you've added it to your database, doesn't mean anything else will happen.
You still need to update your UI.
Add this in after you have executed the query:
comboDriver.Items.Add(Name);
As an aside, you should also wrap the conn.Open() in a try catch as well
I have a Contact Form where the user can add 1 or more (max 5) contacts. Once the user clicks save, the program needs to check the number of contacts submitted and insert into the Contacts_Table accordingly as separate rows. For example, if the user provides 3 contacts, 3 rows should be inserted into the database. The problem here is am able to achieve the goal, but am trying to reduce the number of code lines.
Here is the sample code:
string internalContact = "insert into InternalContact("
+ "Phone, FirstName, Surname)"
+ "values (#Phone, #FirstName, #Surname)";
using (OleDbConnection conn1 = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd1 = new OleDbCommand(internalContact, conn1))
{
conn1.Open();
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = TextBox34.Text;
cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = TextBox42.Text;
cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = TextBox45.Text;
cmd1.ExecuteNonQuery();
if (TextBox64.Text != "")
{
cmd1.Parameters.Clear();
cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = TextBox64.Text;
cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = TextBox65.Text;
cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = TextBox69.Text;
cmd1.ExecuteNonQuery();
}
conn1.Close();
}
}
I would create a struct list and pass all contact info to the method.
struct contactInfo
{
public string FirstName;
public string Surname;
public string Phone;
}
private void insertContacts (List<contactInfo> pList)
{
using (OleDbConnection conn1 = new OleDbConnection(ConnString))
{
conn1.Open();
foreach (contactInfo info in pList)
{
using (OleDbCommand cmd1 = new OleDbCommand(internalContact, conn1))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = info.FirstName;
cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = info.Surname;
cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = info.Phone;
cmd1.ExecuteNonQuery();
}
}
conn1.Close();
}
}
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;
}
}
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())
{
//
}