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);
Related
I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();
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"))
}
}
}
I'm trying to make a login facility for Windows Forms Application project. I'm using Visual Studio 2010 and MS Sql Server 2008.
I referenced this article:
http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Here is my database table named user:
I have TextBox1 for user name , TextBox2 for user password and Button1 for starting login process. Here is my code for Button1_Click method:
private void button1_Click(object sender, EventArgs e)
{
string kullaniciAdi; // user name
string sifre; // password
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
myConn.Open();
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from user where u_name='" + textBox1.Text + "';");
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
myConn.Close();
}
I don't have much experience with C# but i think i'm missing something small to do it right. Below i share exception message that i catched. Can you show me what i'm missing? (line 33 is myReader = myCommand.ExecuteReader();)
Considerin given answers, i updated my try block as in below but it still does not work.
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where u_name=#user");
SqlCommand myCommand = new SqlCommand(myQuery, myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
if (textBox2.Text.Equals(sifre))
{
Form2 admnPnl = new Form2();
admnPnl.Show();
}
}
After changing whole code as below by sine's suggestion, screenshot is also below:
And i think, somehow i cannot assign password in database to the string sifre.
code:
string sifre = "";
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "EKS";
builder.UserID = "sa";
builder.Password = "123";
using (var conn = new SqlConnection(builder.ToString()))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if (tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
if (textBox2.Text.Equals(sifre))
{
try
{
AdminPanel admnPnl = new AdminPanel();
admnPnl.Show();
}
catch (Exception y)
{
MessageBox.Show(y.ToString());
}
}
else
{
MessageBox.Show("incorrect password!");
}
}
}
}
User is a reserved keyword in T-SQL. You should use it with square brackets like [User].
And you should use parameterized sql instead. This kind of string concatenations are open for SQL Injection attacks.
string myQuery = "select u_password from [user] where u_name=#user";
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Try to put user into [ ] because it is a reseved Keyword in T-SQL and use Parameters, your code is open to SQL-Injection!
private void button1_Click(object sender, EventArgs e)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "servername";
builder.InitialCatalog = "databasename";
builder.UserID = "username";
builder.Password = "yourpassword";
using(var conn = new SqlConnection(builder.ToString()))
{
using(var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if(tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
}
}
}
}
USER is a reserved word in T-SQL
Try putting [] around reserved words.
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
user is a keyword.
Change it to something like
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
Futher to that I recomend you have a look at Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
User is a reserved keyword in SQL, you need to do this:
select u_password from [user] where u_name=#user
And as ever, with basic SQL questions, you should always use parameterised queries to prevent people from running any old commands on your DB via a textbox.
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
SqlConnection cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");
SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();
The error message
Executenonquery connection property has not been initialized.
the problem with your current code is that you have not set the Connection property of the SqlCommand object. Try this,
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
and you must also parameterized the values set on the name
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name=#name";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
FULL CODE
string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = #"DataSource=dbedu.cs.vsb.cz\SQLDB;
Persist Security Info=True;
User ID=*****;
Password=*******";
string sqlStatement = #"UPDATE navaznost_ukolu
SET finish = #finish
WHERE Name = #Name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlStatement;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
use using statement for propr object disposal
use try-catch block to properly handle objects
The error is self-explanatory, you have not assigned the connection to the command. You can use the constructor:
using(var cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
"UPDATE navaznost_ukolu SET finish=#finish where Name=#Name"
, cn))
{
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.Parameters.AddWithValue("#finish", finish);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
Note that i've also used a sql-parameter for the Name and using statements to ensure that anything implementing IDisposable gets disposed, even in case of an exception. This will also close the connection.
I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}