Reader not showing any data on search? - c#

I n this sample of code when the execution get there on the while(reader.read()) part.. it not enters the loop and shows there is not any data for this query. I have tried the commented things in it.. that too doesn't worked out. suggest me what's wrong in this code?
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constr))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =" + " '" + "#TableName" + "'", connection);
// SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ActivityIndex';
command.Parameters.Add("#TableName", SqlDbType.NVarChar).Value = listSelectTable.Text;
//SqlCommand command = new SqlCommand();
//command.CommandType = CommandType.Text;
//command.Connection = connection;
//command.CommandText = String.Format("SELECT [column_name] FROM information_schema.columns WHERE table_name = '{0}'", listSelectTable.Text);
/*using (command)
{*/
listSelectColumn.Items.Clear();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
listSelectColumn.Items.Add((string)reader["COLUMN_NAME"]);
}
listSelectColumn.Items.Add("ALL");
}
/*}*/
connection.Close();
}

When you pass parameter separately no need to decorate.
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constr))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =#TableName", connection);
command.Parameters.Add("#TableName", SqlDbType.NVarChar).Value = listSelectTable.Text;
listSelectColumn.Items.Clear();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
listSelectColumn.Items.Add((string)reader["COLUMN_NAME"]);
}
listSelectColumn.Items.Add("ALL");
}
connection.Close();
}

Try modifying your code as follows
SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #TableName" , connection);
command.Parameters.Add("#TableName", SqlDbType.NVarChar);
command.Parameters["#TableName"].Value = listSelectTable.Text;

Try this:-
SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME =#TableName", connection);
There is no need to add quotes in your query, since you are specifying that in command parameters. Also, no need to use your commented code since you are aleady specifying Connection' & 'CommandType is Text by default.

Related

How to update records in SQL Server database through asp.net?

I'm writing this code in asp.net but still it's not updating record in a SQL Server database:
SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();
while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+ "' ", conn);
Proper way to use ado.net:
var newId = count + 1;
var roomType = typeRadioButtonList1.SelectedItem.ToString();
using (var connection = new SqlConnection("your db connection string here"))
{
var query = "UPDATE [roomdetail] SET [rid] = #rid WHERE [rid] = 0 AND roomtype = #roomType";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#rid", newId);
command.Parameters.AddWithValue("#roomType", roomType);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
}
You are Missing ExecuteNonQuery Method Write Below code
SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();
while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+ "' ", conn);
cmd3.executeNonQuery();
Assuming the connection is already opened, in your while loop you are missing the following statement:
cmd3.ExecuteNonQuery();
You have to execute the command in order for the database to be updated.

How to add items to a comboBox in C# from two tables?

I'd really appreciate if someone could help me figure out how to fill two comboboxes data from two different tables. The code below doesn't seem to be working for me.
string command = "SELECT * FROM [Course]";
string command2 = "SELECT * FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
SqlDataReader reader2 = db.commandExecute(command2);
while (reader.Read())
{
comboBox2.Items.Add(reader["CourseID"].ToString());
}
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
reader.Close();
reader2.Close();
db.connectionEnd();
Instead of using two queries you can try like this
string command = "SELECT * FROM [Course] UNION ALL SELECT * FROM [Module]";
If you have columns mismatch problem while joining query use NULL as Column1 for extra column
Eg-:
string command = "SELECT CUSTID AS ID FROM [Course] UNION ALL SELECT ModuleID AS ID FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
while (reader.Read())
{
comboBox2.Items.Add(reader["ID"].ToString());
}
reader.Close();
db.connectionEnd();
Update
I thought that you are going to add two table values in same comboxbox that's why posted above code.
Can you try this code it worked for me
SqlConnection con = new SqlConnection("Data Source=pcname;Initial Catalog=database;Persist Security Info=True;User ID=sa;Password=123");
SqlCommand cmd = new SqlCommand("SELECT * FROM [Course]", con);
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [Module]", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ComboBox1.Items.Add(dr(0).ToString);
}
}
dr.Close();
SqlDataReader dr1 = cmd1.ExecuteReader;
if (dr1.HasRows)
{
while (dr1.Read)
{
ComboBox2.Items.Add(dr1(0).ToString);
}
}
dr1.close();
con.close();
Hope this help you
Change your code
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
with
while (reader2.Read())
{
// Change here the name of reader
comboBox1.Items.Add(reader2["ModuleID"].ToString());
}

how to use executereader to read one value

I want to read an int value from my table. but I faced with error
this is my code. please help me to edit my code.
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
SqlDataReader rdr = cmd.ExecuteReader();
// loop over all rows returned by SqlDataReader
while(rdr.Read())
{
RemainedChargeLbl.Text=rdr.GetString(0);
}
To read one value you don't need reader. Use SqlCommand.ExecuteScalar Method which executes query and returns first column of the first row in result set returned by query:
int value = (int)cmd.ExecuteScalcar();
BTW it's better to create command object with sqlc.CreateCommand() - it creates appropriate command and automatically assigns connection to it.
You are not assigning connection object sqlc to the SqlCommand.
Add this:
cmd.Connection=sqlc;
Complete Solution:
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection=sqlc;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
RemainedChargeLbl.Text =((int) cmd.ExecuteScalar()).ToString();
Use this code:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username);
cmd.Parameters.AddWithValue("#id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}

Unable to execute cmd.ExecuteReader()

Here is the code where i'm trying to retrieve user name using emailid.
string query="select name from userdetails where emailid=" + email + ";" ;
connection.Open();
MySqlCommand cmd = new MySqlCommand(query,connection);
MySqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
uname = (string)rd["emailid"];
return uname;
}
parameterized the value to avoid from SQL Injection
string query="select name from userdetails where emailid=#email" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("#email", email);
Try this code snippet:
string connStr = "connection string here";
string sqlStatement = "select name from userdetails where emailid=#email";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
using(MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
comm.CommandText = sqlStatement;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#email", email);
try
{
conn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
// other codes
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exception
Put you emailin sigle qoute because it is varchar like this..
string query="select name from userdetails where emailid='" + email + "';" ;
But this may cause SQL Injection...so use this...
string query="select name from userdetails where emailid=#email;" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("#email",email);
Update your select query like this with adding email in single quote:
string query = "select name from userdetails where emailid='" + email +"';";
or
you can use parametrized query like this :
string query="select name from userdetails where emailid=#email" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("#email", email);

How list items from table with wildcard in sqlite using c#?

How can I get elements from table using wildcard?
I've made code something like that.
What is wron here? Is it safe if I put this into loop ?
private void Pokaz()
{
String sql = "SELECT [element] FROM [table] LIKE #Word";
SQLiteConnection connection = new SQLiteConnection(#"Data Source=C:\Temp2\dictionary.s3db");
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
DataTable dt = new DataTable();
SQLiteDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
connection.Close();
dataGridView1.DataSource = dt;
}
I changed to String sql = "SELECT [element] FROM [table] where [element] LIKE \'#Word\'";
But now I get empty result.
I tried also this method. Fixed and works. Still above not.
List<string> list = new List<string>();
string connectionString = #"Data Source=C:\Temp2\dictionary.s3db";
string sql = "SELECT [element] FROM [table] where [element] LIKE \'%dog%\' ";
using (var connection = new SQLiteConnection(connectionString))
{
using (var command = new SQLiteCommand(sql, connection))
{
connection.Open();
SQLiteDataReader rd = command.ExecuteReader();
while (rd.Read())
{
list.Add(rd[0].ToString());
}
}
}
Have you tried
String insSQL = "SELECT [element] FROM [table] like #Word"; //% search with prefix and postfix
SQLiteCommand cmd = new SQLiteCommand(insSQL);
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
?

Categories