Hi i am trying to create a validation that checks if its an Unsuccessful SQL Query - if no results are returned, it should catch this error and display a message on screen 'No record found for Client ID: [number]'
The query i currently have fetching the information is below.
protected void ClientSearchBtn_Click(object sender, EventArgs e)
{
//string ClientID = ClientIDTxt.Text;
//Database connection. Calls from web.config.
string MyConnectionString = ConfigurationManager.ConnectionStrings
["RCADSCONNECTION"].ConnectionString;
//SQL Connection
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = MyConnectionString;
//myConnection.Open();
//SQL string
try
{
SqlCommand cmd = new SqlCommand("SELECT CN.ClientID, CI.NNN, CN.GivenName1, CN.Surname, CI.DateOfBirth, CI.Gender FROM [RioOds].dbo.ClientIndex CI LEFT JOIN [RioOds].[dbo].[ClientName] CN ON CN.ClientID = CI.ClientID AND CN.AliasType = '1' AND CN.EndDate IS NULL WHERE CN.ClientID = #clientid", myConnection);
cmd.Parameters.Add("#clientid", SqlDbType.Int).Value = ClientIDTxt.Text;
myConnection.Open();
var reader = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (i != 0)
{
sb.Append(" | ");
}
sb.Append(reader[i].ToString());
}
sb.AppendLine();
ClientIDCell.Text = reader[0].ToString();
NNNCell.Text = reader[1].ToString();
FirstNameCell.Text = reader[2].ToString();
SurnameCell.Text = reader[3].ToString();
DobCell.Text = reader[4].ToString();
GenderCell.Text = reader[5].ToString();
}
//Show the results table
queryResultsTable.Visible = true;
ResultsLabel.Text = sb.ToString();
submitButton.Enabled = true;
resultsButton.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
myConnection.Close();
}
myConnection.Close();
}
I am unsure how to go by doing this. I do understand itll be an if statement but unsure how to compare an sql query return to being null.
reader.Read() returns true if there are more rows to read. First time only if it is false that means reader has no data.
if(!reader.Read())
//Your message
else
{
do
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (i != 0)
{
sb.Append(" | ");
}
sb.Append(reader[i].ToString());
}
sb.AppendLine();
ClientIDCell.Text = reader[0].ToString();
NNNCell.Text = reader[1].ToString();
FirstNameCell.Text = reader[2].ToString();
SurnameCell.Text = reader[3].ToString();
DobCell.Text = reader[4].ToString();
GenderCell.Text = reader[5].ToString();
} while (reader.Read());
}
Another option is to check the property HasRows on reader. It's true when there is data in it.
if(!reader.HasRows)
//Your error message goes from here
else
//Do your stuff
Related
I'm retrieving some information from an MSSQL via SQLDataReader, but while debugging it I notice in some cases the reader clears the result view with the error "Enumeration yielded no results" see the screenshot Before Running passing Read(),
After passing read()
this is my code,the error happens on getActiveUsers() method.
getDatabases() works just fine. could someone help me? cheers
public partial class automation : System.Web.UI.Page
{
SqlConnection con;
static List<ActiveUsers> activeUsers = new List<ActiveUsers>();
protected void Page_Load(object sender, EventArgs e)
{
ASPxGridView1.DataSource = activeUsers.ToList();
}
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
con = new System.Data.SqlClient.SqlConnection(sqlconn);
var cmd = new SqlCommand(SqlQuery, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<ActiveUsers> results = new List<ActiveUsers>();
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
con.Close();
return results;
}
public void getActiveUsers()
{
activeUsers.Clear();
List<ActiveUsers> Databases= getDatabases();
SqlConnection conn = new SqlConnection();
string SqlQuery = "select [disabled], [ADMN_Users1].[Record_Id] ,[ADMN_Users].[User_Id] from admn_Users1 inner join [ADMN_Users] on [ADMN_Users1].[record_Id] = [ADMN_Users].[Record_Id] Where [disabled] & 0x2 = 0 ";
for (int i = 0;i < Databases.Count;i++)
{
conn.ConnectionString =
"Data Source=MAXSQLCLUS01;" +
"Initial Catalog=" + Databases[i].ToString()+";"+
"User id=sa;" +
"Password=Max1m1zer;";
var cmd = new SqlCommand(SqlQuery, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int NumberOfUsersCounter = 0 ;
//TODO Select Enabled users
if (reader.Read())
{
while (reader.Read())
{
string user = String.Format("{0}", reader["User_Id"]);
//logic to remove system users
if (user.Equals("master", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("emailuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("webuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
{
NumberOfUsersCounter++;
}
}
ActiveUsers newEntry = new ActiveUsers();
newEntry.NumberActiveUsers = NumberOfUsersCounter.ToString();
newEntry.DatabaseName = Databases[i].DatabaseName.ToString();
newEntry.ClientName = Databases[i].ClientName.ToString();
activeUsers.Add(newEntry);
}
conn.Close();
//Add to ActiveUsers list
}
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = activeUsers.ToList();
ASPxGridView1.DataBind();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
getActiveUsers();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
ASPxGridView1.DataBind();
ASPxGridViewExporter1.Landscape = true;
ASPxGridViewExporter1.FileName = "User Count Report";
ASPxGridViewExporter1.WriteXlsToResponse();
}
}
}
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
use this
if (reader.HasRows)
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
your if Condition is wrong
if(reader.Read()) ==> is Wrong
Read() is not return boolean Value
use HasRows to check rows in SQLDataReader
You are skipping the first result. if (reader.Read()) { while(reader.Read()) {.... Remove the enclosing if, all it does is see if there is a row and retrieve it but then you do not read it, instead you do it again in the if so the first result is always discarded.
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
using(con = new System.Data.SqlClient.SqlConnection(sqlconn))
using(var cmd = new SqlCommand(SqlQuery, con))
{
con.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
List<ActiveUsers> results = new List<ActiveUsers>();
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = reader.GetString(0);
company.ClientName = reader.GetString(1);
results.Add(company);
}
}
}
return results;
}
Side notes:
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]) would be better written as company.DatabaseName = reader.GetString(0). The same goes for the next line. No need to use string.Format and you are specifying the columns and order in the query so use the ordinal index so get the native value.
I would recommend you wrap the SqlConnection and SqlDataReader in using blocks to ensure they are closed/disposed after use even in the event of an exception.
Error Returned:
"No value given for one or more required parameters."
String Array to pass to function:
String[,] arrParams = new String[1, 2] {
{"#ToUpper_user_id", id}
};
Value of id:
"test" (without the quotes)
SQL:
strSQL = "select * from users where ToUpper_user_id = ?;";
SQL Function Call:
if (jdb.getdb_data(strSQL, arrParams, strTableName, out dsGet, out strTechMessage))
{
...
}
Function that calls to get data from the db:
public static bool getdb_data(String strSQL, String[,] arrParams, String strTableName, out DataSet dsGet, out String strTechMessage)
{
bool boolRC = true;
String key = String.Empty;
String val = String.Empty;
dsGet = new DataSet();
strTechMessage = String.Empty;
String strSQL_Empty = String.Empty;
string connectionString = jdb.getConnString();
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
if (arrParams.GetLength(0) > 0)
{
for (int i = 0; i < arrParams.GetLength(0); i++)
{
for (int j = 0; j < arrParams.GetLength(1); j++)
{
if (j.Equals(0)) { key = arrParams[i, j]; }
if (j.Equals(1)) { val = arrParams[i, j]; }
}
command.Parameters.AddWithValue(key, val);
}
}
else
{
boolRC = false;
strTechMessage = "No parameters found";
}
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
if (boolRC)
{
try
{
connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, connection);
adapter.Fill(dsGet, strTableName);
}
catch (Exception ex)
{
boolRC = false;
strTechMessage = ex.Message;
}
}
}
return boolRC;
}
Please help - I think I am goin' insane! (The Update CRUD all works with parameters . . . just the select code is giving me the error.)
In "get_dbdata(...)" above, I should have have had:
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
instead of:
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, connection);
In the code, both the sql and parameters have already been added to the command above.
Works now!
I would like to see all of the data with column names in my logfile.
private static void ExecuteSQL()
{
string conn = "User ID=SYSDBA;Password=masterkey;Database=XX.18.137.XXX:C:/ER.TDB;DataSource==XX.18.137.XXX;Charset=NONE;";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "SELECT * FROM RDB$RELATIONS";
FbCommand myCommand = new FbCommand(sql, myConnection);
try
{
myConnection.Open();
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
// Log.WriteLog(myReader["rdb$relation_name"].ToString());
}
myConnection.Close();
}
catch (Exception e)
{
Log.WriteLog(e.ToString());
}
}
Right now it's only showing me the rdb$relation_name column.
I want to check the different tables for which I don't have the column's name.
All you need to do is iterate over all fields printing their names before iterating the results:
private static void ExecuteSQL()
{
string conn = "User ID=SYSDBA;Password=masterkey;Database=XX.18.137.XXX:C:/ER.TDB;DataSource==XX.18.137.XXX;Charset=NONE;";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "SELECT * FROM RDB$RELATIONS";
FbCommand myCommand = new FbCommand(sql, myConnection);
try
{
myConnection.Open();
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
// 1. print all field names
for (int i = 0; i < myReader.FieldCount; i++)
{
Log.WriteLog(myReader.GetName(i));
}
// 2. print each record
while (myReader.Read())
{
// 3. for each record, print every field value
for (int i = 0; i < myReader.FieldCount; i++)
{
Log.WriteLog(myReader[i].ToString());
}
}
myConnection.Close();
}
catch (Exception e)
{
Log.WriteLog(e.ToString());
}
}
I am pretty sure, that this will give ugly output as it prints every output to a new line. You should be able to change this to print the fields and each record in rows.
public static List<string> GetColumnNames(string queryString)
{
string result = string.Empty;
List<string> listOfColumns = new List<string>();
try
{
using (FbConnection conn = new FbConnection(connString))
{
conn.Open();
using (FbCommand cmd = new FbCommand(queryString, conn))
{
// Call Read before accessing data.
FbDataReader reader = cmd.ExecuteReader();
if (reader.FieldCount > 0)
{
for (int i = 0; i < reader.FieldCount; i++)
{
listOfColumns.Add(reader.GetName(i));
}
}
}
}
}
catch (Exception e)
{
BinwatchLogging.Log(e);
}
return listOfColumns;
// return result;
}
where querystring is your query (eg: select * from yourtablename) and connstring is your firebird connectionstring
i am trying to insert items in a database using SQLite but when i call loadfunction i receive an error like out of index. I think the problem is when i call add function. I checked parameters values and all seems to be ok, but the elements are not inserted in the table. Bellow you will see my table, add function and load function.
The table:
CREATE TABLE `Fisiere` (
`Nume` TEXT,
`Dimensiune` INTEGER,
`Data` BLOB,
`Rating_imdb` REAL,
`Cale` TEXT
);
The insert function:
public void addFisier(DirectorVideo[] directors)
{
var dbCommand = new SQLiteCommand();
dbCommand.Connection = _dbConnection;
dbCommand.CommandText = "insert into Fisiere(Nume, Dimensiune, Data, Rating_imdb, Cale) values(#nume, #dimensiune, #data, #rating_imdb, #cale);";
try {
_dbConnection.Open();
dbCommand.Transaction = _dbConnection.BeginTransaction();
for (int i = 0; i < directors.Length - 1; i++)
{
for (int j = 0; j < directors[i].nrFisiere; j++)
{
var numeParam = new SQLiteParameter("#nume");
numeParam.Value = directors[i].fisiere[j].numeFisier;
var dimensiuneParam = new SQLiteParameter("#dimensiune");
dimensiuneParam.Value = directors[i].fisiere[j].dimensiune;
var dataParam = new SQLiteParameter("#data");
dataParam.Value = directors[i].fisiere[j].data;
var ratingParam = new SQLiteParameter("rating_imdb");
IMDb rat = new IMDb(directors[i].fisiere[j].numeFisier);
ratingParam.Value = rat.Rating;
var caleParam = new SQLiteParameter("cale");
caleParam.Value = directors[i].cale;
Console.WriteLine(numeParam.Value);
dbCommand.Parameters.Add(numeParam);
dbCommand.Parameters.Add(dimensiuneParam);
dbCommand.Parameters.Add(dataParam);
dbCommand.Parameters.Add(ratingParam);
dbCommand.Parameters.Add(caleParam);
Console.WriteLine(caleParam.Value);
dbCommand.Transaction.Commit();
Console.WriteLine("A fost inserat");
}
}
}
catch (Exception)
{
Console.WriteLine("muie");
dbCommand.Transaction.Rollback();
throw;
}
finally
{
if (_dbConnection.State != ConnectionState.Closed) _dbConnection.Close();
}
}
Load file function
public void LoadFiles()
{
const string stringSql = "PRAGMA database_list";
try
{
_dbConnection.Open();
SQLiteCommand sqlCommand = new SQLiteCommand(stringSql, _dbConnection);
SQLiteDataReader sqlReader = sqlCommand.ExecuteReader();
try
{
while (sqlReader.Read())
{
Console.WriteLine("se afiseaza");
Console.WriteLine((long)sqlReader["Id_fisier"]);
Console.WriteLine((string)sqlReader["Nume"]);
Console.WriteLine((long)sqlReader["Dimensiune"]);
Console.WriteLine(DateTime.Parse((string)sqlReader["Data"]));
Console.WriteLine((long)sqlReader["Rating_imdb"]);
Console.WriteLine((string)sqlReader["Cale"]);
}
}
finally
{
// Always call Close when done reading.
sqlReader.Close();
}
}
finally
{
if (_dbConnection.State != ConnectionState.Closed) _dbConnection.Close();
}
}
You are going to need to Commit your transaction. You call BeginTransaction() but you never commit your transaction so the data never gets written to the DB. Check this out for the details and workflow with Transactions. https://www.sqlite.org/lang_transaction.html
The other problem is that your Transactions and your Commands are all out of order. You need to execute your commands within your transaction and then commit the transaction.
public void addFisier(DirectorVideo[] directors)
{
SQLiteTransaction dbTrans;
try
{
_dbConnection.Open();
// Start Transaction first.
dbTrans = _dbConnection.BeginTransaction();
for (int i = 0; i < directors.Length - 1; i++)
{
for (int j = 0; j < directors[i].nrFisiere; j++)
{
// Create commands that run based on your number of inserts.
var dbCommand = new SQLiteCommand();
dbCommand.Connection = _dbConnection;
dbCommand.CommandText = "insert into Fisiere(Nume, Dimensiune, Data, Rating_imdb, Cale) values(#nume, #dimensiune, #data, #rating_imdb, #cale);";
dbCommand.Transaction = dbTrans;
var numeParam = new SQLiteParameter("#nume");
numeParam.Value = directors[i].fisiere[j].numeFisier;
var dimensiuneParam = new SQLiteParameter("#dimensiune");
dimensiuneParam.Value = directors[i].fisiere[j].dimensiune;
var dataParam = new SQLiteParameter("#data");
dataParam.Value = directors[i].fisiere[j].data;
var ratingParam = new SQLiteParameter("rating_imdb");
IMDb rat = new IMDb(directors[i].fisiere[j].numeFisier);
ratingParam.Value = rat;
var caleParam = new SQLiteParameter("cale");
caleParam.Value = directors[i].cale;
Console.WriteLine(numeParam.Value);
dbCommand.Parameters.Add(numeParam);
dbCommand.Parameters.Add(dimensiuneParam);
dbCommand.Parameters.Add(dataParam);
dbCommand.Parameters.Add(ratingParam);
dbCommand.Parameters.Add(caleParam);
Console.WriteLine(caleParam.Value);
Console.WriteLine("A fost inserat");
// Actually execute the commands.
dbCommand.ExecuteNonQuery();
}
}
// If everything is good, commit the transaction.
dbTrans.Commit();
}
catch (Exception)
{
Console.WriteLine("muie");
dbTrans.Rollback();
throw;
}
finally
{
if (_dbConnection.State != ConnectionState.Closed) _dbConnection.Close();
}
}
Here is also a snippet from the SQLiteTransaction Class documentation. I suggest reading it: https://www.devart.com/dotconnect/sqlite/docs/Devart.Data.SQLite~Devart.Data.SQLite.SQLiteTransaction.html
public static void RunSQLiteTransaction(string myConnString) {
using (SQLiteConnection sqConnection = new SQLiteConnection(myConnString)) {
sqConnection.Open();
// Start a local transaction
SQLiteTransaction myTrans = sqConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
SQLiteCommand sqCommand = sqConnection.CreateCommand();
try {
sqCommand.CommandText = "INSERT INTO Dept(DeptNo, DName) Values(52, 'DEVELOPMENT')";
sqCommand.ExecuteNonQuery();
sqCommand.CommandText = "INSERT INTO Dept(DeptNo, DName) Values(62, 'PRODUCTION')";
sqCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception e) {
myTrans.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally {
sqCommand.Dispose();
myTrans.Dispose();
}
}
}
I have looked at the other questions with this title and I think the problem is something local with my code that I am missing.
The function that this button preforms is to calculate the points/rewards that a person earns based on the transaction total. For example, $10 = 1 point, 19=1 point, 20=2. 10 Points = 1 Rewards points, which is equal to a ten dollar credit.
My Code receives the title error message. I will include the entire function for completeness.
private void button1_Click(object sender, EventArgs e)
{
try{
string cs = #"server=localhost;userid=root;password=root;database=dockingbay94";
MySqlConnection conn;
//MySqlDataReader rdr = null;
using (conn = new MySqlConnection(cs));
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
string input = textBox2.Text;
MySqlCommand myCommand2 = conn.CreateCommand();
myCommand2.CommandText = "SELECT Points FROM members WHERE id = #input";
MySqlDataAdapter MyAdapter2 = new MySqlDataAdapter();
MyAdapter2.SelectCommand = myCommand2;
double transaction = Convert.ToDouble(textBox3.Text);
double tmp_transaction = Math.Floor(transaction);
string transaction_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
double pointsbefore = (tmp_transaction / 10.0);
int currentpoints = Convert.ToInt32(pointsbefore);
int rewards = 0;
int oldpoints = 0;
string temp = "";
pointsbefore = Math.Floor(pointsbefore);
int new_points;
double tmp_rewards = 0.0;
double tmp_points;
int new_rewards;
oldpoints = (int)myCommand2.ExecuteScalar();
new_points = currentpoints + oldpoints;
tmp_points = new_points / 10;
int tmp_rewards2 = 0;
if (new_points > 10)
{
tmp_rewards = Math.Floor(tmp_points);
tmp_rewards2 = Convert.ToInt32(tmp_rewards);
}
else if (new_points == 10)
{
tmp_rewards2 = 1;
}
else
{
tmp_rewards2 = 0;
}
new_rewards = rewards + tmp_rewards2;
int points_left = 0;
if (new_points > 10)
{
for (int i = 10; i < new_points; i++)
{
points_left++;
}
}
else if (new_points == 10)
{
points_left = 0;
}
else if (new_points < 10)
{
for (int i = 0; i < new_points; i++)
{
points_left++;
}
}
string query = "UPDATE members Set Points=#Points, rewards_collected=#Rewards, transaction_total=#Transaction, transaction_date=#TransactionDate" + "WHERE id = #input;";
MySqlCommand cmdDataBase = new MySqlCommand(query, conn);
cmdDataBase.Parameters.Add("#input", SqlDbType.Int).Value = Convert.ToInt32(textBox2.Text);
cmdDataBase.Parameters.AddWithValue("#Points", new_points);
cmdDataBase.Parameters.AddWithValue("#Rewards", new_rewards);
cmdDataBase.Parameters.AddWithValue("#Transaction", textBox3.Text);
cmdDataBase.Parameters.AddWithValue("#TransationDate", transaction_date);
MySqlDataReader myReader2;
myReader2 = cmdDataBase.ExecuteReader();
MessageBox.Show("Data Updated");
if(conn.State == ConnectionState.Open){
conn.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I am not sure where the error could be. Probably not sending the right value.
Thanks
This line is wrong
using (conn = new MySqlConnection(cs));
Remove the semicolon and include everything that needs the MySqlConnection variable inside a {} block
using (MySqlConnection conn = new MySqlConnection(cs))
{
// No need to test if the connection is not open....
conn.Open();
.........
// Not needed (at least from your code above
// MySqlDataAdapter MyAdapter2 = new MySqlDataAdapter();
// MyAdapter2.SelectCommand = myCommand2;
... calcs follow here
// Attention here, if the query returns null (no input match) this line will throw
oldpoints = (int)myCommand2.ExecuteScalar();
.... other calcs here
MySqlCommand cmdDataBase = new MySqlCommand(query, conn);
cmdDataBase.Parameters.Add("#input", SqlDbType.Int).Value = Convert.ToInt32(textBox2.Text);
cmdDataBase.Parameters.AddWithValue("#Points", new_points);
cmdDataBase.Parameters.AddWithValue("#Rewards", new_rewards);
cmdDataBase.Parameters.AddWithValue("#Transaction", textBox3.Text);
cmdDataBase.Parameters.AddWithValue("#TransationDate", transaction_date);
// Use ExecuteNonQuery for INSERT/UPDATE/DELETE and other DDL calla
cmdDataBase.ExecuteNonQuery();
// Not needed
// MySqlDataReader myReader2;
// myReader2 = cmdDataBase.ExecuteReader();
// Not needed, the using block will close and dispose the connection
if(conn.State == ConnectionState.Open)
conn.Close();
}
There is also another error in the final query. Missing a space between #TransactionDate parameter and the WHERE clause. In cases where a long SQL command text is needed I find very useful the verbatim string line character continuation #
string query = #"UPDATE members Set Points=#Points, rewards_collected=#Rewards,
transaction_total=#Transaction, transaction_date=#TransactionDate
WHERE id = #input;";