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"))
}
}
}
Related
I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}
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.
I get this error when trying to insert data into my database.
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'User'.
Here is the code:
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(
Properties.Settings.Default.BlackBookDBConnectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO User (Username, Password, SecurityQuestionOne, "
+ "SecurityQuestionTwo, SecurityAnswerOne, SecurityAnswerTwo); VALUES ("
+ txtRegisterUsername.Text + ","
+ txtRegisterPassword.Text + ","
+ lstRegisterSecurityQuestionOne.SelectedText + ","
+ lstRegisterSecurityQuestionTwo.SelectedItem + ","
+ txtRegisterSecurityAnswerOne.Text + ","
+ txtRegisterSecurityAnswerTwo.Text + ")";
cmd.CommandText = "INSERT INTO USer ()";
cmd.Connection = connection1;
connection1.Open();
cmd.ExecuteNonQuery();
connection1.Close();
}
I have edited my code. However it still does not insert anything into my database for some reason.
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (#Username,#Password,#QuestionOne,#AnswerOne,#QuestionTwo,#AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("AnswerTwo", answerTwo);
command.Connection = connection1;
connection1.Open();
command.ExecuteNonQuery();
connection1.Close();
}
Remove this line:
cmd.CommandText = "INSERT INTO USer ()";
EDIT
After looking at your new code, you have wrong parameters names (missing #). You should change your code to this:
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("#Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("#Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("#QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("#QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("#AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("#AnswerTwo", answerTwo);
Remove second line assigning cmd.CommandText - it's overwriting the first one
User is a keyword in SQL server, if you have a table with that name (which you should not) enclose it into square brackets:
cmd.CommandText = "INSERT INTO [User] ...
On a side note - learn about parametrized queries. They're a great way to avois SQL injection attacks (not to mention confusing mess of string concatenation)
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
connection1.Open();
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (#Username,#Password,#QuestionOne,#AnswerOne,#QuestionTwo,#AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.Add("#Username", SqlDbType.VarChar, 200).Value = userName;
string password = txtRegisterRepeatPassword.Text;
command.Parameters.Add("#Password", SqlDbType.VarChar, 200).Value = password;
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.Add("#QuestionOne", SqlDbType.VarChar, 200).Value = questionOne;
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.Add("#QuestionTwo", SqlDbType.VarChar, 200).Value = questionTwo;
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.Add("#AnswerOne", SqlDbType.VarChar, 200).Value = answerOne;
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.Add("#AnswerTwo", SqlDbType.VarChar, 200).Value = answerTwo;
command.ExecuteNonQuery();
connection1.Close();
}
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);
I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.