private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["DeathWish"].ToString();
con.Open();
string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text);
SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader dr = cmd.ExecuteReader();
string[] s = new string[] { };
while (dr.Read())
{
s = dr["Decision"].ToString().Split(',');
}
int length = s.Length;
for (int i = 0; i < length - 1; i++)
{
string fetr = s[i];
for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
{
if (checkedListBox1.Items[j].ToString() == s[i])
{
checkedListBox1.SetItemChecked(j, true);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text); is the line with error.
2nd picture edited* I wanted to retrieve a specific value on the database using checkedboxlist
this is the image:
error msg
i wanted to retrieve the data on the database and show the specific value
So a couple of things:
Consider enclosing your DB access code in a using block, and instantiating a new connection using your connection string. This ensures that - either by error or by completion of the block - the connection is correctly closed and disposed off.
Secondly, moving the try/catch inside of the using statement is good practice if you're also working with transactions, as you can commit on completion or rollback in your catch block.
Finally, never use string concatenation to build your queries, when the source of the data you're concatenating with comes from a user control (hell, just never do it). SQL injection is still the OWASP number 3 security risk in software to this day, and it needs to be squashed.
Mandatory reading:
OWASP - Top 10 Web Application Security Risks
SQL Injection - Wikipedia
SQL Injection - Technet
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
// a SqlConnection enclosed in a `using` statement will auto-close, and will ensure other resources are correctly disposed
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DeathWish"].ToString()))
{
try
{
con.Open()
string[] s = new string[] { };
string query = "Select [ID],Decision from Data where [ID]=#id order by Decision";
SqlCommand cmd = new SqlCommand(query, con);
SqlParameter idParam = new SqlParameter();
idParam.ParameterName = "#id";
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s = dr["Decision"].ToString().Split(',');
}
int length = s.Length;
for (int i = 0; i < length - 1; i++)
{
string fetr = s[i];
for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
{
if (checkedListBox1.Items[j].ToString() == s[i])
{
checkedListBox1.SetItemChecked(j, true);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
}
}
Your Connection is (still) open, so you have to check if it is closed. If it is you can open a new connection.
So try this:
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
if(con.State == ConnectionState.Closed)
{
con.Open();
}
con.ConnectionString = ConfigurationManager.ConnectionStrings["DeathWish"].ToString();
string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text);
SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader dr = cmd.ExecuteReader();
string[] s = new string[] { };
while (dr.Read())
{
s = dr["Decision"].ToString().Split(',');
}
int length = s.Length;
for (int i = 0; i < length - 1; i++)
{
string fetr = s[i];
for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
{
if (checkedListBox1.Items[j].ToString() == s[i])
{
checkedListBox1.SetItemChecked(j, true);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
Related
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();
}
}
}
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
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;";
I have a problem in listview.I my listview i have five columns(question_number,question_text,start_time,end_time,status). the first four columns will be fetch the data from the database.once the data has entered i have to compare the starttime and with the current time.once the starttime is greater than current time then i have to update the status column as expired. otherwise i have to say not expired.
I have attached the code what i did so for.
I do no how to get the status updated in the status column.Please any one help me.thanks in advance.
public void GetData()
{
try
{
myConnection = new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dish;Persist Security Info=True;Data Source=ENMEDIA-CCDDFE5\ENMEDIA");
//myConnection.Open();
//SqlDataReader dr = new SqlCommand("SELECT question_text,question_id FROM otvtbl_question ", myConnection).ExecuteReader();
// listView1.Columns.Clear();
listView1.Items.Clear();
myConnection.Open();
String MyString1 = string.Format("SELECT question_id,question_text,start_time,end_time FROM otvtbl_question");
SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = MyString1;
dr = cmd.ExecuteReader();
//Adding The Column Name From The DataBase
for (int i = 0; i < dr.FieldCount; i++)
{
ColumnHeader ch = new ColumnHeader();
ch.Text = dr.GetName(i);
//listView1.Columns.Add(ch);
}
ListViewItem itmX;
//Adding the Items To The Each Column
while (dr.Read())
{
itmX = new ListViewItem();
itmX.Text = dr.GetValue(0).ToString();
for (int i = 1; i < dr.FieldCount; i++)
{
itmX.SubItems.Add(dr.GetValue(i).ToString());
}
listView1.Items.Add(itmX);
}
dr.Close();
myConnection.Close();
}
catch (Exception ex)
{
//Error Message While Fetching
MessageBox.Show("Error While Fetching the data From the DataBase" + ex);
}
finally
{
//Closing The Connection
if (dr != null)
dr.Close();
if (myConnection.State == ConnectionState.Open)
myConnection.Close();
}
Something like this?
while (dr.Read())
{
...
listView1.Items.Add(itmX);
if (dr.GetDateTime(2) > dr.GetDateTime(3))
{
itmX.SubItems.Add("Expired");
}
}