private void Update_Click(object sender, EventArgs e)
{
string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");
OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location=? WHERE itemID='1' ", con);
com.Parameters.Add("#loca", OleDbType.VarChar).Value = loca;
con.Open();
try
{
com.ExecuteNonQuery();
}
catch(Exception f)
{
MessageBox.Show(f.Message);
//MessageBox.Show("Given Data is not Valid", "Cannot Add", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
gridview();
}
Here I have changed the code no error m getting is
No value given for one or more required parameters
Update query is not working so please help me with it.
In C# you need to add an actual parameter object and give it a value:
string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");
OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location= ? WHERE itemID='1'", con);
com.Parameters.Add("#loca", OleDbType.VarWChar).Value = loca ?? (object)DBNull.Value;
Some other suggestions/habits to get in to:
Wrap your connections and commands in using blocks so that they get disposed of in a timely manner
Do not just catch an exception and show a vague message. Either include the exception details or log it somewhere so that you know what the actual error is.
Related
I have a question according to this code. VisualStudio shows no errors or warnings but when I run it, the result is only the exceptionerror ("Something went wrong."). This is how I have always done it before but somehow always worked except for now. Am I missing a simple thing?
protected void Page_Load(object sender, EventArgs e)
{
// Connect
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\royva\documents\visual studio 2013\Projects\CookieMultiView\CookieMultiView\App_Data\Databank.mdb';Persist Security Info=True";
// Execute
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM teachers = ?";// + Request.QueryString["id"];
lbl.Text = "";
cmd.Parameters.AddWithValue("id",Request.QueryString["id"]);
// Read
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
lbl.Text = reader["teacherid"].ToString();
}
}
catch (Exception ex)
{
//lbl.Text = ex.StackTrace;
lbl.Text = "Something went wrong.";
}
finally
{
conn.Close();
}
For Detailed info of the Exception,
catch (Exception ex)
{
//Either you can write log or display in label
lbl.Text = ex.Message;
}
Also check the folder access rights for
Data Source='C:\Users\royva\documents\visual studio 2013\Projects\CookieMultiView\CookieMultiView\App_Data\Databank.mdb'
Programmatically to check for specific files use File.Exists(path), which will return a boolean indicating whether the file at path exists.
And validate if the connection has been established or not.
I have read many other questions about this same thing but it seems the answers do not pertain to how I am performing my code. After adding or deleting a record or row of information to my database from the user interface it does not show in the combo boxes until I restart the application. Maybe someone can enlighten me as I am somewhat new to this. Below is my code when clicking the add button.
private void FBinterface_Load(object sender, EventArgs e)
{
txtSerial.Focus();
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string SerialQuery = "select SerialNumber from Inventory";
command.CommandText = SerialQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboSerial.Items.Add(reader["SerialNumber"]);
}
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtSerial.Text))
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = #"insert into
Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" +
txtSerial.Text + "','" +
txtPart.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
//TO READ DATA
command.ExecuteNonQuery();
MessageBox.Show("Inventory Added");
txtPart.Clear();
txtSerial.Clear();
txtRO.Clear();
txtLocation.Clear();
if (dataGridFB.DataSource != null)
{
dataGridFB.DataSource = null;
}
else
{
dataGridFB.Rows.Clear();
}
txtSerial.Focus();
connection.Close(); // CLOSE HERE OR
// YOU CANNOT ENTER RECORDS SIMULTANEOUSLY
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}
As a simple fix, you may add the following code snippet before the line connection.Close() in the btnAdd_Click event handler:
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string SerialQuery = "select SerialNumber from Inventory";
command.CommandText = SerialQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboSerial.Items.Add(reader["SerialNumber"]);
}
This code snippet will essentially re-bind the ComboBox comboSerial. The same goes to other ComboBoxes if their underlying data is affected by btnAdd_Click procedure. Furthermore, it could be fruitful to create a dedicated procedure (something like ResfreshAllComboBoxes()), place the code similar to the sample snippet above and call it after underlying data change.
Hope this may help.
It's better to put codes in (FBinterface_Load) inside a new method, say FillComboSerial(), and then you have to call that method after inserting each new record right after closing the connection.
I need to insert values into several tables first I have to retrieve university id from table college and then insert faculty name into table faculty and get generated by SQL Server ID. After all of this I have to insert both ids into an other table.
Problem is that I have to close readers and after I do it I can't retrieve those ids from them so variable where they should be saved is null. Here is my code. How to do it correctly?
Sorry I am new to C# and SQL Server.
// reading data into combobox
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from colege", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
comboBox1.Items.Add(myReader["name"].ToString());
// Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
myConnection.Close();
private void button1_Click(object sender, EventArgs e)
{
string item = comboBox1.Text.ToString();
// MessageBox.Show(item);
SqlConnection myConnection = new SqlConnection("user id=bogdan_db;" +
"password=1234;server=localhost;" +
"Trusted_Connection=yes;" +
"database=cafedrascience; " +
"connection timeout=30");
try
{
myConnection.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
// reading data into combobox
String colegeid = null;
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from colege where name like'" + item + "'", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
colegeid = myReader["id"].ToString();
// Console.WriteLine(myReader["Column2"].ToString());
}
myReader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
String facultyid = null;
try
{
SqlDataReader myReader1 = null;
SqlCommand myCommand = new SqlCommand("select * from depart where name like'" + textBox1.Text + "'",
myConnection);
myReader1 = myCommand.ExecuteReader();
while (myReader1.Read())
{
facultyid = myReader1["id"].ToString();
}
myReader1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlCommand myCommand1 = new SqlCommand("INSERT INTO coledge_faculty (coledge_id, faculty_id) " +
"Values ('"+colegeid+"''"+facultyid+"')", myConnection);
myCommand1.ExecuteNonQuery();
// MessageBox.Show(colegeid);
// MessageBox.Show(facultyid);
myConnection.Close();
}
The number one thing I can stress about your code is that you should be using parameterised queries, beyond the obvious risks of SQL Injection, it also protects you against malformed SQL, data truncation through conversion, and it allows you to use cached execution plans.
The next thing to point out is that you should not be using SELECT * in production code, e.g.
SqlCommand myCommand = new SqlCommand("select * from colege where name like'" + item + "'", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
colegeid = myReader["id"].ToString();
// Console.WriteLine(myReader["Column2"].ToString());
}
Why bother retrieving all the columns of colege from the database, then sending them all over the network if you only care about the column id?
Finally your diagnosis of the problem is not correct:
Problem is that I have to close readers and after I do it, I can't retrieve those ids from them, so variable where they should be saved is null
If you assign the string variable colegeid a value you have retrieved from a data reader, it will not be null after you have closed the reader, it will retain the value you assigned. The most likely reason the variable is null is because your reader returns no rows so you never assign it a value.
Now, rant over, I will actually answer your question. You are massively over complicating the issue, you do not need to retrieve the values into your application tier only to insert them to another table, you can do this all in a single query in your database:
INSERT INTO coledge_faculty (coledge_id, faculty_id)
SELECT c.id, d.id
FROM depart AS d
CROSS JOIN colege AS c
WHERE d.Name = #Depart
AND c.Name = #Colege;
Then it would just be a case of calling this SQL from C#:
string item = comboBox1.Text.ToString();
string connectionString = "user id=bogdan_db; password=1234;server=localhost; Trusted_Connection=yes; database=cafedrascience; connection timeout=30";
string sql = #"INSERT INTO coledge_faculty (coledge_id, faculty_id)
SELECT c.id, d.id
FROM depart AS d
CROSS JOIN colege AS c
WHERE d.Name = #Depart
AND c.Name = #Colege;";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Colege", SqlDbType.VarChar, 50).Value = item;
command.Parameters.Add("#Depart", SqlDbType.VarChar, 50).Value = textBox1.Text;
connection.Open();
command.ExecuteNonQuery();
}
It is usually a good idea to use using blocks with objects that implement IDisposable, this will ensure the resources are freed up when you are done with them (Don't confuse this with not being able to reuse the connection, .NET has connection pooling in the background so it will reuse connections for you, you shouldn't keep your SqlConnection object open available in case you need to use it again).
On another unrelated note, I also think you are too liberal with try/catch blocks, or at least not dealing with the exception properly, using this one as an example:
try
{
myConnection.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
If myConnection.Open() does throw an error, you still carry on with the method. You will carry on until you get to here:
SqlCommand myCommand = new SqlCommand("select * from colege where name like'" + item + "'", myConnection);
myReader = myCommand.ExecuteReader();
Where you will get another exception, something along the lines of the command requiring an open and available SqlConnection, so you go to the exception.
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Again you don't exit the method, but carry on, and you will get the same error later when you try and use the connection again. Again the method carries on and you will use the closed connection a third time to try and insert two variables that were never assigned because exceptions were thrown into your database. Fine, use try catch blocks, but do something meaningful with the exception and exit the method.
private void BtnAdd_Click(object sender, EventArgs e)
{
//con.Open();
cmd = new SqlCommand("INSERT INTO TBL_STORE VALUES (N'"+txt_store_name.Text.Trim()+"',N'"+txt_store_adress.Text.Trim()+"',N'"+txt_store_mobile_1.Text.Trim()+"',N'"+txt_store_mobile_2.Text.Trim()+"',N'"+txt_store_Manger.Text.Trim()+"',N'"+txt_store_Details.Text.Trim()+"')");
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#store_name", txt_store_name.Text.Trim());
cmd.Parameters.AddWithValue("#store_adress", txt_store_adress.Text.Trim());
cmd.Parameters.AddWithValue("#store_mobile_1", txt_store_mobile_1.Text.Trim());
cmd.Parameters.AddWithValue("#store_mobile_2", txt_store_mobile_2.Text.Trim());
cmd.Parameters.AddWithValue("#store_manger", txt_store_Manger.Text.Trim());
cmd.Parameters.AddWithValue("#store_details", txt_store_Details.Text.Trim());
cmd.Parameters.AddWithValue("#Id_store", txt_store_number.Text.Trim());
con.Close();
lbl_store.Text="insert is sucess";
//cmd.Parameters.Add("#store_name", SqlDbType.NVarChar, 50).Value = txt_store_name.Text.Trim();
}
I try to learn some coding with Visual C#. I create a form for add and update Access database.
I can successfully add to Access file but I can't update them.
I write a code similar below by some search in internet but I get this error:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
My code is:
public partial class form1 : Form
{
private OleDbConnection con;
private void btnUpDate_Click(object sender, EventArgs e)
{
string FirstName = txtFirstName.Text;
string Family = txtFamily.Text;
string City = txtCity.Text;
string approve = txtapprove.Text;
string OfficeNumber = txtOfficeNumber.Text;
string OfficialDossier = txtOfficialDossier.Text;
string Department = txtDepartment.Text;
string Organization = txtOrganization.Text;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Data Source=F:\\Database.accdb");
string query = "UPDATE Sheet1 SET FirstName=#FirstName, Family=#Family, City=#City, approve=#approve, OfficeNumber=#OfficeNumber, OfficialDossier=#OfficialDossier, Department=#Department, Organization=#Organization WHERE OfficeNumber=#OfficeNumber";
//string query = "UPDATE aspnet_Users SET FirstName=#FirstName, Family=#Family, City=#City, approve=#approve, OfficeNumber=#OfficeNumber, OfficialDossier=#OfficialDossier, Department=#Department WHERE OfficeNumber=#OfficeNumber";
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#OfficeNumber", OfficeNumber);
cmd.Parameters.AddWithValue("#OfficialDossier", OfficialDossier);
cmd.Parameters.AddWithValue("#FirstName", FirstName);
cmd.Parameters.AddWithValue("#Family", Family);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#approve", approve);
cmd.Parameters.AddWithValue("#Department", Department);
cmd.Parameters.AddWithValue("#Organization", Organization);
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException)
{
MessageBox.Show("There is a problem!");
}
finally
{
con.Close();
}
}
}
Where I have mistake? I Don't use of DataSet and DataAdapter. Is problem from there?
I'm using VS 2010
Problem 1: You have not Opened the Connection object oleDBConn which was assigned to the OleDbCommand Object.
You have assigned oleDBConn to OleDbCommand object as below:
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);//here you have assigned oleDbConn
but you have opened different ConnectionObject con as below:
con.Open();
Solution 1:
Replace This: You should always Open the OleDbConnection (oleDBConn) Object which was assigned to the OleDbCOmmand Object.
con.Open();
With This:
oleDBConn.Open();
Problem 2: You have created an Extra connection object con (on top of your btnUpDate_Click function) and by mistake you are working with the same.(Opening and closing the wrong connection object instead of proper one)
Solution 2: Remove the extra connection object created on top of btnUpDate_Click function and replace all con occurences with oleDBConn.
Complete Code:
try
{
oleDBConn.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException ex)
{
MessageBox.Show("There is a problem!"+ex.ToString());
}
finally
{
oleDBConn.Close();
}
I am currently developing an Application for Windows using MySQL and C#. I have the following code:
private void cboCategories_SelectedIndexChanged(object sender, EventArgs e)
{
DatabaseWork dbase = new DatabaseWork();
try
{
dbase.openConnection();
string query = "SELECT * FROM budgetcategory WHERE budc_userID=#userID AND budc_category=#category";
MySqlCommand cmd = new MySqlCommand("", dbase.conn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#userID", userID);
cmd.Parameters.AddWithValue("#category", cboCategories.SelectedItem.ToString());
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
setCatId(reader.GetString("budc_category_id"));
Console.WriteLine("Category ID: " + getCatId());
}
}
catch (MySqlException ex)
{
Console.WriteLine("Cat Error: " + ex.Message);
}
finally
{
dbase.closeConnection();
}
}
For some reason when I debug the code it never goes into the while loop as if nothing was ever returned from the database. But I know there should be something in there.
Thanks for any help you can provide
Just trying to help you debug a little:
Try reducing these three lines:
string query = "SELECT * FROM budgetcategory WHERE budc_userID=#userID AND budc_category=#category";
MySqlCommand cmd = new MySqlCommand("", dbase.conn);
cmd.CommandText = query;
to just:
string query = "SELECT * FROM budgetcategory WHERE budc_userID=#userID AND budc_category=#category";
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);
Now put a breakpoint on those lines that add the parameters, and make sure that userID and especially cboCategories.SelectedItem.ToString() have the values that you expect.
Also, can you confirm that no exception is thrown?
If this is not the case run the query, with those exact values directly against the database and confirm that something is returned.