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();
}
}
Related
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);.
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
Below is the code I'm using to connect to an Access Database.
I'm trying to insert the data (which is a form the user fills in). But always the exception is caught and no data gets inserted.
I've double checked the variable names for spelling errors,they are all correct.
private void addConfirm_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\hospitalApplication\HealthCare.accdb;Persist Security Info=False;";
String name = typedName.Text;
String addr = typedAddr.Text;
String DOB = typedDOB.Text;
String phone = typedPhone.Text;
String emergency = typedEmergency.Text;
String dateOfReg = typedDateReg.Text;
String patientstatus = typedStatus.Text;
String bedNo = typedBed.Text;
String blood = typedBlood.Text;
String visit = typedVisit.Text;
String diagnosis = typedDiagnosis.Text;
String doctorID = typedDoctor.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Patients (Full Name, Address,Date of Birth,Phone No,Emergency Contact,Date of Registration,Patient Status,bedID,Blood Type,Date of Visit,Diagnosis,doctorID) Values(#name, #addr,#DOB,#phone,#emergency,#dateOfReg,#patientstatus,#bedNo,#blood,#visit,#diagnosis,#doctorID)", conn);
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#name", OleDbType.VarChar).Value = name;
cmd.Parameters.Add("#addr", OleDbType.VarChar).Value = addr;
cmd.Parameters.Add("#DOB", OleDbType.VarChar).Value = DOB;
cmd.Parameters.Add("#phone", OleDbType.VarChar).Value = phone;
cmd.Parameters.Add("#emergency", OleDbType.VarChar).Value = emergency;
cmd.Parameters.Add("#dateOfReg", OleDbType.VarChar).Value = dateOfReg;
cmd.Parameters.Add("#patientstatus", OleDbType.VarChar).Value = patientstatus;
cmd.Parameters.Add("#bedNo", OleDbType.Integer).Value = bedNo;
cmd.Parameters.Add("#blood", OleDbType.VarChar).Value = blood;
cmd.Parameters.Add("#visit", OleDbType.VarChar).Value = visit;
cmd.Parameters.Add("#diagnosis", OleDbType.VarChar).Value = diagnosis;
cmd.Parameters.Add("#doctorID", OleDbType.Integer).Value = doctorID;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
Your SQL in invalid. The spaces are confusing the query parser.
The best approach is to not use spaces in your table/column names. But if you must, then you'll need to enclose them in brackets to tell the query parser that both words identify one item. Something like this:
INSERT into Patients ([Full Name], ...
Do this for any table/column name which includes either spaces or reserved words. (You can do this for all of the table/column names if you'd like.)
Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.