This code connect to oracle but not execute query.
I install Oracle Developer Tools for Visual Studio .NET.
And check code is true.
And Oracle.DataAccess.dll.
And It works query in sql developer.
And everything code is true but not execute statement .
help me.
bool result = false;
string connst =System.Configuration.ConfigurationSettings.AppSettings["OISCS"];
Console.Write(connst);
OleDbConnection dbConn = new OleDbConnection();
dbConn.ConnectionString = connst;
OleDbCommand dbCom = new OleDbCommand(" SELECT * FROM OIS.USERINFo WHERE USERID= '" + UserID + "';", dbConn);
dbCom.CommandType = System.Data.CommandType.Text;
dbCom.CommandTimeout = 30;
try
{
dbConn.Open();
OleDbDataReader dbReader = (OleDbDataReader)dbCom.ExecuteReader();
dbReader.Read();
}
catch (Exception e)
{
throw e;
}
return result;
You should change the lines where you initialize the dbReader:
OleDbDataReader dbReader = (OleDbDataReader) dbCom.ExecuteReader();
The code you have now throws a NullReferenceException because you never initialize dbReader.
UPDATE: Now that the question is updated, this should no longer be the case...
Related
I am currently writing a code using C# and SQLite. There is an error being throwing stating that the database is locked twice in a message box.
The query works on SQLite DB Browser however, when it is placed in C# code it throws the error.
Here is the code that is giving me an error:
cmd.CommandText = "UPDATE customers SET Bill = Bill - "+textBox2.Text+" WHERE customers.CustomerID = " + textBox1.Text + ";";
There seems to be an issue with the equals sign, might be something wrong with the arithmetic process.
Complete code:
SQLiteConnection myconn = new SQLiteConnection(#"Data Source = C:\Users\chick\Newspaper.db");
SQLiteCommand cmd = myconn.CreateCommand();
cmd.CommandText = "UPDATE customers SET Bill = (Bill - "+textBox2.Text+") WHERE customers.CustomerID = " + textBox1.Text + ";";
myconn.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Succesfully Update");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
UPDATE:
Changed format to using() {} however it is still not working. Program is crashing
New Code:
using (SQLiteConnection myconn = new SQLiteConnection(#"Data Source = C:\Users\chick\Newspaper.db"))
{
var sql = "Update customers SET Bill = Bill - #pay WHERE customers.CustomerID = #cid;";
myconn.Open();
using (var cmd = new SQLiteCommand(sql, myconn))
{
cmd.Parameters.AddWithValue("#cid", textBox1.Text);
cmd.Parameters.AddWithValue("#pay", textBox2.Text);
cmd.ExecuteNonQuery();
}
}
The problem is that some other part of the program (or some other program) still has an active transaction.
You must properly clean up all commands that access the database, i.e., use using everywhere.
Thank you to all that have answered. We realized the issue was that we never closed the reader in previous code.
I am using c# and I cannot get any vaue. The data returns null. This is my code.
SQLiteConnection DBConnection;
DBConnection = GetMyconnection();
DBConnection.Open();
string DBCommand = "SELECT * FROM settings WHERE setting_key = '" + setting_key + "' LIMIT 1";
using (SQLiteCommand sqlCommand = new SQLiteCommand(DBCommand, DBConnection))
{
using (SQLiteDataReader DBDataReader = sqlCommand.ExecuteReader())
{
if (DBDataReader.Read())
{
object data = sqlCommand.ExecuteScalar();
return DBDataReader.GetString(DBDataReader.GetOrdinal("setting_value"));
}
else
{
return "Error";
}
}
}
DBConnection.Close();
This code is placed in a global helper function which I call from a form.
Kindly help.
The main item is saw was that you were running an ExecuteScalar on the same command as the ExecuteReader and I could see no reason why. Other things I noted was that you were concatenating the statement instead of using parameters, you only needed one value but were using SELECT *, and there was no exception handling. I would have a Unique Index on the settingkey column to speed up the query and prevent duplicates, so you don't need to have the LIMIT 1 on the command
I rolled this up trying to use as much of your code as possible. I altered the SQL command to get the one value that you wanted, only using the ExecuteScalar method, and using the conditional operator instead of the if...then block. The actual command has been wrapped in a try...catch for exception handling and will provide error feedback
string ReturnValue;
SQLiteConnection DBConnection;
DBConnection = GetMyconnection();
DBConnection.Open();
string DBCommand = "SELECT setting_value FROM settings WHERE setting_key = #settingkey LIMIT 1";
using (SQLiteCommand sqlCommand = new SQLiteCommand(DBCommand, DBConnection)) {
sqlCommand.parameters.AddWithValue("#settingkey", setting_key);
try {
object data = sqlCommand.ExecuteScalar();
ReturnValue = (data != null) ? data.ToString() : "Error";
}
catch (Exception ex) { ReturnValue = "Exception: " + ex.Message; }
}
DBConnection.Close();
return ReturnValue;
this code read a list of row but if your query is ok work.
string sql = "SELECT * FROM settings WHERE setting_key = '" + setting_key + "' LIMIT 1";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
Console.WriteLine("Name: " + reader["setting_value"] + "\tScore: " + reader["score"]);
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'm currently working on a simple windows form bug reporter for university and am having trouble. I'm trying to create a query where the user can only delete the bug if:
The bug name exists
The user logged in matches the user that reported the bug.
Currently no matter which use is logged in, the query always returns 'Incorrect User Logged In!' and doesn't delete the bug.
I am a novice at both C# and MySQL, so I'm sure my code isn't the best way of writing it. I apologize if it is hard to read.
EDIT
Here is my current code based on the below answer which still doesnt work. I currently get could not find specified colum in results: bug_submitted_by
connection = new MySqlConnection(connectionString);
string check = "SELECT COUNT(*) FROM bugs WHERE bug_name ='" + this.txt_bug_name.Text + "'AND bug_submitted_by='" + this.lbl_user.Text + "';";
MySqlCommand cmd = new MySqlCommand(check, connection);
MySqlDataReader reader;
connection.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
if (reader.GetString("bug_submitted_by").Equals(this.lbl_user.Text))
{
reader.Close();
cmd.Dispose();
string query = "DELETE from bugs WHERE bug_name='" + this.txt_bug_name.Text + "';";
MySqlCommand cmd2 = new MySqlCommand(query, connection);
MySqlDataReader reader2;
reader2 = cmd2.ExecuteReader();
lbl_message.Text = "Bug Deleted!";
reader2.Close();
cmd2.Dispose();
connection.Close();
load_table();
Combo_selection();
reset(this);
}
else
{
lbl_message.Text = "Incorrect user!";
reader.Close();
cmd.Dispose();
connection.Close();
cb_names.SelectedIndex = -1;
}
}
else
{
lbl_message.Text = "Bug Doesn't Exist!";
}
As a side note first, I recommend you look into parameterized queries in C#. I will use that sort of syntax in my answer, but I believe it will be easy enough for you to understand. Given that you are trying to do multiple things (check if bug exists, check if bug was written by that user, delete that bug if condition is met) I recommend you break it up into pieces and put them all back together.
To start, we can just write a query to see if a bug exists. We can be smart and select both the bug name, and who it was submitted by:
using(var conn = new MySqlConnection(ConnectionString)
{
conn.Open();
using(var cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT bug_name, bug_submitted_by FROM bugs WHERE bug_name = #name";
cmd.Parameters.AddWithValue("#name", this.txt_bug_name.Text);
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
// Will fill in next
}
}
}
}
Side note: If you're unfamiliar with using, see this question for some insight. This is so you don't have to worry about disposing the objects, they will be disposed once you leave scope of the using block.
So, the above query pulls the row from the table where the bug name matches the input. The inner if statement is used to make sure a row was returned. If it was, check the username and react accordingly. If it doesn't, react accordingly like this:
using(var conn = new MySqlConnection(ConnectionString)
{
conn.Open();
using(var cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT bug_name, bug_submitted_by FROM bugs WHERE bug_name = #name";
cmd.Parameters.AddWithValue("#name", this.txt_bug_name.Text);
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
// We got a row
if(reader.GetString("bug_submitted_by").Equals(this.lbl_user.Text))
{
// If the username matches delete it
using(var cmd2 = new MySqlCommand())
{
cmd2.Connection = conn;
cmd2.CommandText = "DELETE FROM bugs WHERE bug_name = #name";
cmd2.Parameters.AddWithValue("#name", this.txt_bug_name.Text);
cmd2.ExecuteNonQuery();
lbl_message.Text = "Bug Deleted!";
}
}
else
{
// Username doesn't match
lbl_message.Text = "Incorrect user!";
}
}
else
{
// We didn't get a row
lbl_message = "Bug Doesn't Exist!";
}
}
}
}
What this query does not do is protect against the situation where a specific bug name appears twice. If your database restricts that, then you're good. If it doesn't, you'll need to implement some check to make sure you only got one row back.
Please don't hit database with subsequent requests. Not only this unnecessary but may also be misleading because a lot may happen between two calls that you make in a multiuser environment. Another session may already updated or deletes this row.
You can do it all in one go
DELETE
FROM bugs
WHERE bug_name = 'bug1'
AND bug_submitted_by = 'John';
Here is a SQLFiddle demo
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.