SqliteDataReader doesn't work in C#? - c#

I have some data stored in a SQLite database which I want to display on a webpage in C#. I searched for the right thing to do but only found console.writeline, and beside that the SqliteDataReader function is not working. This is my code:
protected void Page_Load(object sender, EventArgs e)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db"))
{
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
command.Connection = conn;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
string test = ("Name: " + reader["name"] + "\tScore: " + reader["score"]);
command.ExecuteNonQuery();
conn.Close();
}
}
What should I do?
Thanks in advance,
Elias

It seems that you've forgot to put the actual query to perform:
command.CommandText = "...";
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
//TODO: do not hardcode connection string, move it to settings
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
// var for simplicity
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
//TODO: put the right SQL to perform here
command.CommandText =
#"select name,
score
from MyTable";
using (var reader = command.ExecuteReader()) {
string test = "";
// do we have any data to read?
//DONE: try not building string but using formatting (or string interpolation)
if (reader.Read())
test = $"Name: {reader["name"]}\tScore: {reader["score"]}";
//TODO: so you've got "test" string; do what you want with it
}
}
//DONE: you don't want command.ExecuteNonQuery(), but command.ExecuteReader()
//DONE: you don't want conn.Close() - "using" will do it for you
}
}

Related

Populate CheckedListBox from Database and list

I'm trying to populate a checkedlistbox from a list
my approach:
SqlCommand getlocationnames = new SqlCommand("allLocationNames", conn);
getlocationnames.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = getlocationnames.ExecuteReader();
List<locations> results = new List<locations>();
while (dr.Read())
{
locations newItem = new locations();
newItem.loc_name = dr.GetString(0);
results.Add(newItem);
}
dr.Close();
foreach (var result in results)
{
checkedListBox1.Items.Add(result);
}
Does some one see what I'm missing here?
Try this approach (instead of two loops, one loop is used in this approach, which increases the application's speed):
Output:
SQL (a StoredProcedure which is already created in the database):
Create Procedure AllValues As Select * From YourTableName
Go
C#:
System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection("Data Source =.;" + "AttachDbFilename = " + Application.StartupPath + #"\YourDataBaseName.mdf;" + "Integrated Security = True;");
private void AddButton_Click(object sender, EventArgs e)
{
Connection.Open();
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand();
Command.Connection = Connection;
Command.CommandType = CommandType.StoredProcedure;
Command.CommandText = "AllValues";
System.Data.SqlClient.SqlDataReader DataReader = Command.ExecuteReader();
List<object> results = new List<object>();
//DataReader[0] means the first column of the table
//DataReader[1] means the second column of the table
while (DataReader.Read())
{
results.Add(string.Join(null, "Country = ", DataReader[0].ToString(), "\t\t", "Capital = ", DataReader[1].ToString()));
}
Connection.Close();
checkedListBox.Items.Clear();
checkedListBox.Items.AddRange(results.ToArray());
}
private void ClearButton_Click(object sender, EventArgs e)
{
checkedListBox.Items.Clear();
}
Tested in:
Visual Studio 2017, .NET Framework 4.5.2, Windows Forms, SQL Server 12.0.6024.0

Output Not Displaying in TextBox in C#

I am new to C# and I have connected it with Oracle11g and using Visual Studio 2013 as a tool. I am trying to display a 'name ' that is being returned by a query to a textbox but it is neither displaying an Error Message nor displaying the Output. Pleases help me to resolve this problem. Thanks... here is my code..
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr.GetString(0);
conn.Dispose();
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
after setting textBox1.Text = dr.GetString(0);
it is giving me the attached exception.
Array indexes start at index zero, not 1. The returned string (if any) is at
textBox1.Text = dr.GetString(0);
A more correct way to write your code is the following
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
// Use the using statements around disposable objects....
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
// These two parameters could be passed directly in the
// OracleCommand constructor....
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
// Again using statement around disposable objects
using(OracleDataReader dr = cmd.ExecuteReader())
{
// Check if you have a record or not
if(dr.Read())
textBox1.Text = dr.GetString(0);
}
}
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
And if your code is supposed to return just a single record with a single column then you can use the more performant ExecuteScalar without building an OracleDataReader
// Again using statement around disposable objects
object result = cmd.ExecuteScalar();
if(result != null)
textBox1.Text = result.ToString();

How to delay my program while reading from a database C#

I have a mess with trying to read line by line from a MS Access database and display it on the screen when between every display there are a few seconds of sleeping.
I am using System.Threading as you can see but it seems the sleeping is happening before the program displays the records and when the sleeping is over only the last record is displayed without displaying the previous.
Here is my code, I will really appreciate any help!
private void com_start_Click(object sender, EventArgs e)
{
try
{
string ConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\MyBrainWash\Englishdb.accdb;";
OleDbConnection Con = new OleDbConnection(ConString);
Con.Open();
check_connection.Text = "succeeded";
OleDbCommand command = new OleDbCommand();
command.Connection = Con;
command.CommandText = "Select * From words";
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
Thread.Sleep(30000);
}
}
reader.Close();
Con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
UI controls lab_word and lab_definition.Text will be updated after whole com_start_Click method completes.
That is why you see that only last row have been shown.
You need "release" UI thread after reading every row for 3 seconds for updating UI controls with new values.
I think async/await approach suits very good this purpose.
Mark button click with async keyword.
private async void com_start_Click(object sender, EventArgs e)
{
string ConString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\MyBrainWash\Englishdb.accdb;";
using (var Con = new OleDbConnection(ConString))
{
Con.Open();
check_connection.Text = "successed";
using (var command = new OleDbCommand())
{
command.Connection = Con;
command.CommandText = "Select * From words";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
await Task.Delay(30000);
}
}
}
}
}
You can also use asynchronous methods of OleDbConnection, OleDbCommand and OleDbReader
private async void com_start_Click(object sender, EventArgs e)
{
string ConString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\MyBrainWash\Englishdb.accdb;";
using (var Con = new OleDbConnection(ConString))
{
await Con.OpenAsync();
check_connection.Text = "successed";
using (var command = new OleDbCommand())
{
command.Connection = Con;
command.CommandText = "Select * From words";
using (var reader = await command.ExecuteReader())
{
while (await reader.ReadAsync())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
await Task.Delay(30000);
}
}
}
}
}

Invalid attempt to call Read when reader is closed

I am having a problem with the sql datareader. Whenever I try to read data it gives me an error saying invalid attemp to call Read when the reader is closed. Please help me figure out the problem
private void button1_Click(object sender, EventArgs e)
{
string name = this.textBox1.Text;
string connstring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Gardezi\Documents\Visual Studio 2012\Projects\homeWork2\homeWork2\Database1.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(connstring);
string query = "Select * from diaryDB";
SqlCommand com = new SqlCommand(query, con);
SqlParameter p = new SqlParameter("name", name);
con.Open();
SqlDataReader d = com.ExecuteReader();
con.Close();
deleteResult r = new deleteResult(d);
r.Show();
}
this is the constructor of deleteResult
public deleteResult(SqlDataReader d)
{
InitializeComponent();
while (d.Read())
{
this.comboBox1.Items.Add((d["Title"] +"-" +d["Description"]).ToString());
}
}
You can't read after closing the connection.
Just change this part of your code:
FROM
(...)
con.Close();
deleteResult r = new deleteResult(d);
(...)
TO
(...)
deleteResult r = new deleteResult(d);
con.Close();
(...)
Please try to use the using statement that correctly enclose the connection, the command and the reader in appropriate blocks.
private void button1_Click(object sender, EventArgs e)
{
string name = this.textBox1.Text;
string connstring = #"....";
string query = "Select * from diaryDB";
using(SqlConnection con = new SqlConnection(connstring))
using(SqlCommand com = new SqlCommand(query, con))
{
SqlParameter p = new SqlParameter("name", name);
con.Open();
using(SqlDataReader d = com.ExecuteReader())
{
deleteResult r = new deleteResult(d);
r.Show();
}
}
}
In this way the connection is kept open while you read from the reader. This is essential to avoid the error.
The more important point is that you don't have to worry to close and dispose the connection when it is no more needed. The exit from the using block close and dispose the connection, the command and the reader ALSO in case of exceptions.

Using Image Stored in Database (image path)

I want this button's image use the image stored in database (image path)...
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string connString = "Server=Localhost;Database=test;Uid=*****;password=*****;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = ("Select link from testtable where ID=" + a);
try
{
conn.Open();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
button11.Image = reader["path"].ToString();
}
}
I think the error lies in "reader["path"].ToString();" but I don't know what syntax to use.
If you stored the path to the image file on the disk in the path column, you should laod the image:
string path = (string)reader["path"];
button11.Image = Image.FromFile(path);
Side note: Never pass the values directly from a user input to a database query. It is vulnerable to sql injection attacks. Use parameters instead:
command.CommandText = "Select link from testtable where ID=#id";
command.Parameters.AddWithValue("#id", int.Parse(a));
try this:
while (reader.Read())
{
string path = reader.GetString(0);
button11.Image = Image.FromFile(path);
}
Try this: ( Written right to answer box, may be there are typo! )
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string imagePath;
string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand command = conn.CreateCommand())
{
command.CommandText = "Select link from testtable where ID=#id";
command.Parameters.AddWithValue("#id", int.Parse(a));
try
{
conn.Open();
imagePath= (string)command.ExecuteScalar();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
button11.Image = Image.FromFile(imagePath);
}
}

Categories