I want to get max value form database if database not empty. Program works fine but it gives No Current Row message on start. I've query like this,
public int GetMaxValue(String table, String column, int columnIndex)
{
try
{
int values = -1;
String query = "SELECT MAX(" + column + ") FROM " + table;
SQLiteCommand sQLiteCommand = new SQLiteCommand(query, sQLiteConnection);
sQLiteCommand.ExecuteNonQuery();
using (SQLiteDataReader sQLiteDataReader = sQLiteCommand.ExecuteReader())
{
if (!sQLiteDataReader.IsDBNull(0))
{
while (sQLiteDataReader.Read())
{
values = sQLiteDataReader.GetInt32(columnIndex);
sQLiteDataReader.Close();
return values;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
and call this method by,
string orderNo = database.GetMaxValue(Database.TABLE_ORDER, Database.INVOICE_NO_ORDER, 0).ToString();
in above function, i've check already if Reader Null then do not continue by this,
if (!sQLiteDataReader.IsDBNull(0))
}
but its not works. Kindly tell how to get rid of No Current Row message
This solve my problem
public Int32 GetMaxValue(String table, String column, int columnIndex)
{
try
{
Int32 values = -1;
String query = "SELECT MAX(" + column + ") FROM " + table;
SQLiteCommand sQLiteCommand = new SQLiteCommand(query, sQLiteConnection);
sQLiteCommand.ExecuteScalar();
using (SQLiteDataReader sQLiteDataReader = sQLiteCommand.ExecuteReader())
{
if (sQLiteDataReader.Read())
{
while (sQLiteDataReader.Read())
{
values = sQLiteDataReader.GetInt32(columnIndex);
return values;
}
}
sQLiteDataReader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
Related
I use this code in my twitch bot to count messages and save them to a database a couple times per minute.
So the current code I have does get the values I want from my database, but I cannot update or insert the values correctly. The insert_cmd does execute, but values in the database does not correspond to the values I try to insert.
affectedRows does return the correct answer of rows that should have been affected. Also when I write out the insert_cmd string, it does look right.
private static void update_messages()
{
try
{
MySql.Data.MySqlClient.MySqlConnection mysql_connection = new MySql.Data.MySqlClient.MySqlConnection();
mysql_connection.ConnectionString = mysql_connection_string;
mysql_connection.Open();
//build query string
string select_cmd = "SELECT * FROM taperen.messages where username in (";
foreach(CountData cd in chat_messages)
{
//Console.WriteLine(cd.username);
select_cmd += "\'" + cd.username + "\',";
}
if(select_cmd == "SELECT * FROM taperen.messages where username in (")
{
mysql_connection.Close();
return;
}
select_cmd = select_cmd.TrimEnd(select_cmd[select_cmd.Length - 1]);
select_cmd += ");";
//Console.WriteLine(select_cmd);
MySql.Data.MySqlClient.MySqlCommand myCommand = mysql_connection.CreateCommand();
myCommand.CommandText = select_cmd;
MySql.Data.MySqlClient.MySqlDataReader reader = myCommand.ExecuteReader();
string insert_cmd = "";
while (reader.Read())
{
string username = reader["username"].ToString();
int index = chat_messages.FindIndex(x => x.username.Equals(username));
int current_online_count = chat_messages[index].online_count;
int current_offline_count = chat_messages[index].offline_count;
int db_online_count = (int)reader["online_count"];
int db_offline_count = (int)reader["offline_count"];
int new_online_count = current_online_count + db_online_count;
int new_offline_count = current_offline_count + db_offline_count;
insert_cmd += $"UPDATE `taperen`.`messages` SET `online_count`='{new_online_count}', `online_count`='{new_offline_count}' WHERE `id`='{reader["id"]}';";
chat_messages.RemoveAt(index);
//Console.WriteLine(username);
}
reader.Close();
mysql_connection.Close();
foreach(CountData cd in chat_messages)
{
insert_cmd += $"INSERT INTO `taperen`.`messages` (`username`, `online_count`, `offline_count`) VALUES ('{cd.username}', '{cd.online_count}', '{cd.offline_count}');";
}
mysql_connection.Open();
//Console.WriteLine(insert_cmd);
myCommand.CommandText = insert_cmd;
int affectedRows = myCommand.ExecuteNonQuery();
Console.WriteLine(affectedRows);
myCommand.Dispose();
mysql_connection.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex.Message);
}
}
The CountData class looks like this:
public class CountData
{
public string username { get; set; }
public int online_count { get; set; }
public int offline_count { get; set; }
}
The database looks like this:
Also if I do something else stupid in my code I appreciate if you could come with some tips :)
In this line you are setting online_count twice, the second instance should (presumably) be offline_count.
insert_cmd += $"UPDATE taperen.messages SET online_count='{new_online_count}', online_count='{new_offline_count}' WHERE id='{reader["id"]}';";
You need to pick out the query generated by your code. And then directly run it into Mysql and then compare what it is returning. It looks mysql return effected rows of last executing query. As you are combining Update first and then Insert, hence the effected rows which are getting for Insert. But you can confirm it by directly running your query. Be sure to comment out the code like this :
// int affectedRows = myCommand.ExecuteNonQuery();
I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!
I am trying to update database on button click. but it always returns 0, and database is not updated.
string query4 = "update Praysettings set value ='" + LocName + "' where id =52;";
db2.ExecuteQuery(query4);
public void ExecuteQuery(string query)
{
string dbPath = Path.Combine (
System.Environment.GetFolderPath (
System.Environment.SpecialFolder.Personal
),
"tzmpo_t.rar"
);
if (File.Exists(dbPath)) {
using (var db = new SQLiteConnection(dbPath))
{
int a = db.Execute(query);
db.Close();
}
}
}
The value already exists? If you are not updating the value then there won't be affected rows. Check if that is the case.
Here is the code I use, may be it helps you:
private void OpenConnection()
{
lock (syncLock)
{
if (_connection == null || _connection.State == ConnectionState.Closed || _connection.State == ConnectionState.Broken)
{
_connection = new SqliteConnection("Data Source=" + DbPath);
_connection.SetPassword(DbKey);
_connection.Open();
}
}
}
private int ExecuteNonQuery(string query)
{
lock (syncLock)
{
OpenConnection();
int rowcount = 0;
using (var command = _connection.CreateCommand())
{
command.CommandText = query;
try
{
rowcount = command.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.Error("ExecuteNonQuery", e.Message + ". Query:" + query);
}
command.Dispose();
}
return rowcount;
}
}
There are two tables customer_invoice and sold_item_details
in customer_invoice table there is column, cus_inv_id (PK)
This cus_inv_id is a foreign key to the sold_item_details
Here is my abstract view of the code,
public void txtRent_PreviewKeyDown(object sender, KeyEventArgs e){
/* This method will Insert values to the customer_invoice table */
CreateOrder();
/* This method will Insert values to the sold_item_details table*/
InsertOrderItem(OrderItem orderItem);
}
Here is my question when insertion query is executed the second query raise a MysqlException of Cannot add or update a child row. I checked in between CreateOrder() and InserOrderItem() whether the insertion process has completed surprisingly it turns out it has succeeded.
for example if i insert value set with cus_inv_id = 1 it will be inserted to the table customer_invoice but when inserting to the sold_item_details table with cus_inv_id (FK) = 1 it raise that exception.
These are the two codes related to those two methods. (I have removed some columns for the ease of the problem)
public void CreateOrder()
{
_connection.open();
var mysqlTrans = _connection.BeginTransaction();
var orderId = -1;
MySqlDataReader sqlDataReader;
try
{
const string query =
"SELECT cus_inv_id FROM customer_invoice " +
"WHERE customer_id = #cusId";
var mysqlCommand1 = new MySqlCommand(query, _connection, mysqlTrans);
mysqlCommand1.Parameters.AddWithValue("#cusId", customerId);
sqlDataReader = mysqlCommand1.ExecuteReader();
if (sqlDataReader.HasRows)
{
sqlDataReader.Read();
orderId = (int) sqlDataReader["cus_inv_id"];
}
sqlDataReader.Close();
if (orderId == -1)
{
var mysqlCommand2 = _connection.CreateCommand();
mysqlCommand2.Connection = _connection;
mysqlCommand2.Transaction = mysqlTrans;
mysqlCommand2.CommandText = "SELECT MAX(cus_inv_id) FROM customer_invoice " +
"HAVING MAX(cus_inv_id) IS NOT NULL";
sqlDataReader = mysqlCommand2.ExecuteReader();
if (sqlDataReader.Read())
{
orderId = (int) sqlDataReader["MAX(cus_inv_id)"] + 1;
}
else
{
orderId += 2;
}
sqlDataReader.Close();
mysqlCommand2.CommandText =
"INSERT INTO customer_invoice(cus_inv_id)" +
" VALUES(#cusInvId)";
mysqlCommand2.Parameters.AddWithValue("#cusInvId", orderId);
mysqlCommand2.ExecuteNonQuery();
}
mysqlTrans.Commit();
_connection.close();
}
catch (Exception ex)
{
MessageBox.Show(ex);
mysqlTrans.Rollback();
}
}
public void InsertOrderItem(OrderItem orderItem)
{
_connection.open();
var mysqlCommand = _connection.CreateCommand();
var mysqlTrans = _connection.BeginTransaction();
mysqlCommand.Connection = _connection;
mysqlCommand.Transaction = mysqlTrans;
try
{
mysqlCommand.CommandText = "SELECT MAX(sold_item_id) FROM sold_item_details " +
"HAVING MAX(sold_item_id) IS NOT NULL";
var sqlDataReader = mysqlCommand.ExecuteReader();
var lastSoldItemId = 1;
if (sqlDataReader.Read())
{
lastSoldItemId = (int) sqlDataReader["MAX(sold_item_id)"] +1;
}
sqlDataReader.Close();
mysqlCommand.CommandText = "INSERT INTO sold_item_details(sold_item_id,cus_inv_id) VALUES(#soldItemId, #cusInvId)";
mysqlCommand.Parameters.AddWithValue("#soldItemId", lastSoldItemId);
mysqlCommand.Parameters.AddWithValue("#cusInvId", orderItem.OrderId);
mysqlCommand.ExecuteNonQuery();
mysqlTrans.Commit();
_connection.close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
mysqlTrans.Rollback();
}
}
I have an difficult situation :
this is my form :
the first button '...' is a btnAllegato. Code :
private void btnAllegato_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
string path = string.Empty;
openFileDialog1.Title = "Seleziona richiestaIT (PDF)..";
openFileDialog1.Filter = ("PDF (.pdf)|*.pdf");
openFileDialog1.FilterIndex = 1;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//salva l'intero path
path = openFileDialog1.FileName;
//nome file + estensione
string temp = openFileDialog1.SafeFileName;
//elimina l'estensione del file con IgnoreCase -> case Unsensitive
temp = Regex.Replace(temp, ".pdf", " ", RegexOptions.IgnoreCase);
//datatime + replace
string timenow = System.DateTime.Now.ToString();
//replace data da gg//mm/aaaa ss:mm:hh -----> ad gg-mm-aaaa_ss-mm-hh
timenow = timenow.Replace(":", "-").Replace("/", "-");//.Replace(" ", " ");
_url = #"\\192.168.5.7\dati\SGI\GESTIONE IT\RichiesteIT\" + temp + timenow + ".pdf";
System.IO.File.Copy(path, _url);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
after i have a button Inserisci >> (btnInserisci)
with this button i Create a DB Query to insert data...
private void btnInserisci_Click(object sender, EventArgs e)
{
try
{
if ((_IDRichiedente != -1) && (_data != string.Empty) && (_url != string.Empty))
{
MessageBox.Show(_url);
QueryAssist qa = new QueryAssist();
string query = "INSERT INTO RICHIESTA_IT(ID_Risorsa, descrizione_richiesta, modulo_pdf, data_richiesta) VALUES('" + _IDRichiedente + "', '" + txtBreveDescrizione.Text + "', '" + _url + "', '" + _data + "');";
MessageBox.Show(query);
qa.runQuery(query);
else
{
MessageBox.Show("Selezionare il richiedente,data o allegato!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
where
private int _IDRichiedente = -1;
private string _data = String.Empty;
private string _url = string.Empty;
is a fields of class.
QueryAssist is my class that connect, run query and disconnect to Access DB.
code :
class QueryAssist
{
System.Data.OleDb.OleDbConnection _OleDBconnection;
public QueryAssist()
{
this._OleDBconnection = null;
}
private bool connectionDB()
{
string connection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\"\\\\192.168.5.7\\dati\\Scambio\\Sviluppo\\Impostazioni temporanea db Censimento\\CensimentoIT.accdb\"";
try
{
_OleDBconnection = new System.Data.OleDb.OleDbConnection(connection);
_OleDBconnection.Open();
return true;
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
}
private void disconnectDB()
{
try
{
_OleDBconnection.Close();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
public System.Data.DataTable runQuery(string query)
{
try
{
if (connectionDB())
{
System.Data.DataTable dataTable = new System.Data.DataTable();
System.Data.OleDb.OleDbCommand sqlQuery = new System.Data.OleDb.OleDbCommand(query, _OleDBconnection);
System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery);
adapter.Fill(dataTable);
disconnectDB();
return dataTable;
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
return null;
}
public int countRowsQueryResult(string query)
{
try
{
if (connectionDB())
{
System.Data.DataTable dataTable = new System.Data.DataTable();
System.Data.OleDb.OleDbCommand sqlQuery = new System.Data.OleDb.OleDbCommand(query, _OleDBconnection);
System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery);
adapter.Fill(dataTable);
disconnectDB();
return dataTable.Rows.Count;
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
return -1;
}
}
At firt time ... The application work good. I selected a file and other data and I click on button 'Inserisci>>' and all working good.
Next step when i want to insert other data ... when i click on '...' button for attachment a file i have the loop OpenFileDialog
To close, i must kill the process.
I have [STAThread] set on main of the program.
Connect to NAS isn't a problem ... I have try in local .. and i have the same problem..
If i click on btn '...' to OpenFileDialg then not click on button 'Inserisci>>'
OpenFileDialog work good for all time ...
But if i click on button 'Inserisci>>' on the next click on button '...' to OpenFileDialog application loop..
Sorry for bad english ..I'm here for clarification
The use of the runQuery method with an INSERT statement could be the cause of your problems. To insert a record you should use an OleDbCommand with the ExecuteNonQuery. A Fill method is used to fill a DataTable.
The fact that the record is inserted anyway happens because the underlying command used to fill the DataTable (ExecuteReader) ignores its sql command text and executes what you have passed. However after that the Fill method expects to fill a DataTable and not having a select statement could be potentially the cause of your problems.
I would use a different method when you need to Update/Delete or Insert new data
public int runNonQuery(string query)
{
try
{
if (connectionDB())
{
OleDbCommand sqlQuery = new OleDbCommand(query, _OleDBconnection);
int rows = sqlQuery.ExecuteNonQuery();
disconnectDB();
return rows;
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return -1;
}
}
There are other problems in your code and are all connected to the way in which you concatenate together the string to form an sql statement. This is know as the worst practice possible with database code. If you take a bit of your time to investigate how to write a parameterized query you will avoid a lot of future problems.