I'm trying to update a database from my program in C#.
Here is my code which connects to the database and the attempts to update the date column in my RoomsTable table. It looks good to me but nothing happens in the database.
updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();
MessageBox.Show("Connected");
string updateCommand = "UPDATE RoomsTable SET Date Checked='9/27/2012'";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);
updateConnection.Close();
updateConnection.Dispose();
I don't know why it isn't working. It looks to me like everything is there.
use OleDBCommand
string updateCommand = "UPDATE RoomsTable SET [Date Checked]='9/27/2012'";
updateCommand = new OleDbCommand(updateCommand, updateConnection);
updateCommand.ExecuteNonQuery();
updateConnection.Close();
maybe you could refractor the code using Using statement and parameterized the query. and column name Date Checked should be escaped with brackets.
string updateCommand = "UPDATE RoomsTable SET [Date Checked]=#checkedDate WHERE ID = #id"; // '9/27/2012'
using (OleDbConnection conn = new OleDbConnection("connectionStringHERE"))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandText = updateCommand;
comm.CommandType = CommandType.Text
comm.Parameters.AddWithValue("#checkedDate", this.dateTimePicker1.Value)
comm.Parameters.AddWithValue("#id", row.roomID);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
you have to write this:
updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();
MessageBox.Show("Connected");
string updateCommand = "UPDATE RoomsTable SET Date Checked= '"+9/27/2012+"' ";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);
updateConnection.Close();
updateConnection.Dispose();
Related
I'm trying to Update the Tables in my .xcs files, but nothing happens.
When I execute the Command the Method ExecuteNonQuery returns 1, which should mean that one row got updated.
My ConncetionString is: "Provider=vfpoledb.1;Data Source=C:\Users\alex\AppData\Local\Temp\vyp1rr0e.et5;Mode=ReadWrite"
try
{
string commandText = "UPDATE ddfld SET descript = ?, comments = ? WHERE identifier = ?";
using (OleDbConnection conn = new OleDbConnection(fConnection.ConnectionString))
using (OleDbCommand cmdSafe = new OleDbCommand(commandText, conn))
{
conn.Open();
cmdSafe.Parameters.AddWithValue("#descript", OleDbType.VarChar).Value = field.Description;
cmdSafe.Parameters.AddWithValue("#comments", OleDbType.VarChar).Value = field.Comments;
cmdSafe.Parameters.AddWithValue("#identifier", OleDbType.Decimal).Value = field.Id;
cmdSafe.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
this doesn't update in my database table. Have I over-looked something?
The values are in the textboxes fine. No errors show, weird.
using (SqlConnection connection = new SqlConnection(#"Data Source = UKMAN1NB10038\SQLEXPRESS; Initial Catalog = TheVets; Integrated Security = True"))
{
SqlCommand command = new SqlCommand("UPDATE OwnerTable SET Owner_Fname =#OwnerFname , Owner_Lname = #OwnerLname, Owner_HouseNo = #OwnerHouse, Owner_Street = #OwnerStreet, Owner_County = #OwnerCounty, Owner_PostCode = #OwnerPost, Owner_Tele = #OwnerTele, Owner_Email = #OwnerEmail WHERE Owner_ID = '" + CB_EDIT_OWNER.SelectedText + "'", connection);
command.CommandType = CommandType.Text;
command.Connection = connection;
command.Parameters.AddWithValue("#OwnerFname", TXT_EDIT_FNAME.Text);
command.Parameters.AddWithValue("#OwnerLname", TXT_EDIT_LNAME.Text);
command.Parameters.AddWithValue("#OwnerHouse", TXT_EDIT_HOUSE.Text);
command.Parameters.AddWithValue("#OwnerStreet", TXT_EDIT_STREET.Text);
command.Parameters.AddWithValue("#OwnerCounty", TXT_EDIT_COUNTY.Text);
command.Parameters.AddWithValue("#OwnerPost", TXT_EDIT_POSTCODE.Text);
command.Parameters.AddWithValue("#OwnerTele", TXT_EDIT_TELE.Text);
command.Parameters.AddWithValue("#OwnerEmail", TXT_EDIT_EMAIL.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
You need to use SelectedItem not SelectedText on the combobox
Replace CB_EDIT_OWNER.SelectedText with:
CB_EDIT_OWNER.SelectedItem
Then this should work.
I have two buttons on a page, one that logs a start time, and one that logs an end time.
The start time button performs an sql insert.
At that point i need to grab the primary key that's create. To do this i want to use the sql command (output inserted).
Then when the stop time is clicked,the row should be update with a stop time using the primary key from the start in the where clause.
I believe insert SQL is correct but i don't know how to pass the primary key to the next command.
Code dump, with what i have so far.
var command1 = "INSERT INTO [Time] ([Start Time], [Work Order]) OUTPUT INSERTED.PrimaryKey VALUES (#StartTime, #Work_Order)";
using (SqlConnection cnn1 = new SqlConnection(cnnString))
{
using (SqlCommand cmd1 = new SqlCommand(command1, cnn1))
{
cmd1.Parameters.AddWithValue("#StartTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd1.Parameters.AddWithValue("#Work_Order", SqlDbType.Int).Value = e.CommandArgument;
cnn1.Open();
Label1.Text = cmd1.ExecuteScalar().ToString();
cnn1.Close();
}
}
var command = "UPDATE [Time] SET [Stop Time] = #StopTime WHERE [PrimaryKey] = #PrimaryKey";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(command, cnn))
{
cmd.Parameters.AddWithValue("#StopTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.Parameters.AddWithValue("#PrimaryKey", *PrimaryKey from INSERT output*
cnn.Open();
cmd.ExecuteNonQuery();
}
}
instead of having it go to the label have it go to an int and then set the label text with the int. Then pass the int on the second part. Declare the int outside the scope of the using statements though or it will be disposed and you will get a null reference exception when you try and call it later.
Edit: To add, this would be better if you convert to stored procs and define the SqlParameter objects (you don't have them, you'll need them).
SqlParameter
int myPK;
var command1 = "INSERT INTO [Time] ([Start Time], [Work Order]) OUTPUT INSERTED.PrimaryKey VALUES (#StartTime, #Work_Order)";
using (SqlConnection cnn1 = new SqlConnection(cnnString))
{
using (SqlCommand cmd1 = new SqlCommand(command1, cnn1))
{
cmd1.Parameters.AddWithValue("#StartTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd1.Parameters.AddWithValue("#Work_Order", SqlDbType.Int).Value = e.CommandArgument;
cnn1.Open();
myPk = Convert.ToInt32(cmd1.ExecuteScalar());
Label1.Text = myPk.ToString();
cnn1.Close();
}
}
var command = "UPDATE [Time] SET [Stop Time] = #StopTime WHERE [PrimaryKey] = #PrimaryKey";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(command, cnn))
{
cmd.Parameters.AddWithValue("#StopTime", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.Parameters.AddWithValue("#PrimaryKey", myPK);
FindControl("Work_OrderLabel"); ;
cnn.Open();
cmd.ExecuteNonQuery();
}
}
I am facing error in following Query.According to my knowledge I have written everything perfectly fine. But its giving error that:
"there is an error in update query"
string insert_query = "update aho set read=?,pick=? where Cont_no='" + contract_no + "'";
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = insert_query;
//ocmd.Parameters.AddWithValue("#contrct_no", contract.Text.ToString());
ocmd.Parameters.AddWithValue("#read_val", Convert.ToInt32(read.Text));
ocmd.Parameters.AddWithValue("#pic_val", Convert.ToInt32(pick.Text));
ocmd.Connection = conn;
ocmd.ExecuteNonQuery();
You didn't gave us too much information but..
I think your Cont_no type is some numerical type, not one of the character type. Looks like that's why you get error when you try to add it with ''.
For example like;
Cont_no = '123'
Try this one;
string insert_query = "update aho set [read]=?,pick=? where Cont_no=?";
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = insert_query;
ocmd.Parameters.AddWithValue("#read_val", Convert.ToInt32(read.Text));
ocmd.Parameters.AddWithValue("#pic_val", Convert.ToInt32(pick.Text));
ocmd.Parameters.AddWithValue("#contrct_no", contract_no);
ocmd.Connection = conn;
ocmd.ExecuteNonQuery();
EDIT: HansUp is totally right. Read is a reserved keyword. You should use it with square brackets like [Read] in your query.
In your query string you consider parameters by priority, but when you create them you are giving them a name.
According to http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx, OleDbCommand does not support named parameters.
Look at this example (source: http://www.java2s.com/Code/CSharp/Database-ADO.net/PassparametertoOleDbCommand.htm):
using System;
using System.Data;
using System.Data.OleDb;
public class Prepare {
public static void Main () {
String connect = "Provider=Microsoft.JET.OLEDB.4.0;data source=.\\Employee.mdb";
OleDbConnection con = new OleDbConnection(connect);
con.Open();
Console.WriteLine("Made the connection to the database");
OleDbCommand cmd1 = con.CreateCommand();
cmd1.CommandText = "SELECT ID FROM Employee "
+ "WHERE id BETWEEN ? AND ?";
OleDbParameter p1 = new OleDbParameter();
OleDbParameter p2 = new OleDbParameter();
cmd1.Parameters.Add(p1);
cmd1.Parameters.Add(p2);
p1.Value = "01";
p2.Value = "03";
OleDbDataReader reader = cmd1.ExecuteReader();
while(reader.Read())
Console.WriteLine("{0}", reader.GetInt32(0));
reader.Close();
con.Close();
}
}
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.