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
Related
When executing this query with parameters added as values, i get an error saying my syntax is wrong. I tried following multiple tutorials, looking up questions here is stack overflow, and when comparing, they seem the same, but mine does not seem to work.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\\Users\\fidyc\\OneDrive\\Desktop\\ProgrII.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT Product_Orders(order_ID,plankCount,thickness,width,height)VALUES(#order_ID, #plankCount, #thickness, #width, #height)");
cmd.Parameters.Add("#order_ID", OleDbType.Integer).Value = orderID;
cmd.Parameters.Add("#plankCount", OleDbType.Decimal).Value = plankCount;
cmd.Parameters.Add("#thickness", OleDbType.Decimal).Value = thickness;
cmd.Parameters.Add("#width", OleDbType.Decimal).Value = width;
cmd.Parameters.Add("#height", OleDbType.Decimal).Value = height;
cmd.Connection = con;
con.Open();
if (con.State == ConnectionState.Open)
{
/*try
{*/
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
/*}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
con.Close();
}*/
}
Edit: values are passed to the function
public static void Push(int orderID, decimal plankCount, decimal thickness, decimal width, decimal height)
{
The problem turned out to be the count column name, as sql has a count command, it needs to be
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,[count],thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
instead of
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,count,thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO bookRated "+
"([firstName], [lastName]) "+
"VALUES(#firstName, #lastName)";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#firstName", firstName),
new OleDbParameter("#lastName", lastName),
});
cmd.ExecuteNonQuery();
}
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.)
what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I have started to learn asp.net. I am using VS 2013 Express for C#.
How to make that a some if case to check a duplicate value and if this value is exists then I get a red summary about it and can't insert to DB else insert to database and too with update button.
Can you help?
SqlConnection con = new SqlConnection(#"Data Source=TSS\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
When you say check if a value exists, what fields should not have duplicates? Those are the fields you have to write a select statement for to check if they exist first.
Example
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "select lastname from asmenys where lastname = #lastname";
comm.Parameters.AddWithValue("#lastname", lastname.Text);
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Values exist");
}
else
{
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
}
I have an method like below in C# and i'm gonna to parameterize my query but name field get null value in database .testTable(id,name) and id is auto increament.mysql ver is 5.6
private void buttonTest_Click(object sender, EventArgs e)
{
string query = "insert into testdb.testTable(name) VALUES (#name) ;";
MySqlConnection conDataBase = new MySqlConnection(myfunctions.ConnString);
conDataBase.Open();
MySqlCommand cmd = new MySqlCommand(query, conDataBase);
try
{
cmd.Connection = conDataBase;
cmd.Parameters.AddWithValue("#name","John");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}
try this in place of varchar,50 enter your dbtype
string query = "insert into testdb.testTable(name) VALUES(_name) ;";
and
cmd.Connection = conDataBase;
cmd.Parameters.Add("_name", MySqlDbType.VarChar, 50).Value = "John";
cmd.ExecuteNonQuery();
Try like this
command.Parameters.Add("#name", SqlDbType.VarChar,50);
command.Parameters["#name"].Value = "john";