I have a login form that I wanna select the userID (which is in the form of an int) from the database, and store it as a string.
string insertQuery =
"SELECT UserID FROM Customers WHERE Email = #Email AND Password = #Password";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#Email", tbEmail.Text);
com.Parameters.AddWithValue("#Password", tbPassword.Text);
string result = (string)com.ExecuteScalar();
But after I login, I get this error:
System.InvalidCastException: 'Unable to cast object of type
'System.Int32' to type 'System.String'.
What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:
// Keep Sql being readable
string insertQuery =
#"SELECT UserID
FROM Customers
WHERE Email = #Email
AND Password = #Password";
// Do not forget to dispose IDisposable
using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
com.Parameters.AddWithValue("#Email", tbEmail.Text);
com.Parameters.AddWithValue("#Password", tbPassword.Text);
using (var reader = com.ExecuteReader()) {
string result = reader.Read()
? Convert.ToString(reader[0]) // record exists
: null; // cursor is empty
//TODO: put relevant code which works with result here
}
}
You can try using like below
string result = Convert.ToString(com.ExecuteScalar());
ExecuteScalar returns Object type and you can convert it into which ever type you like
public override object ExecuteScalar ();
You can call it's ToString() method and it returns string form of it's value.
Try this,
string result = string.Empty;
SqlCommand com = new SqlCommand(..);
..
object executedResult = com.ExecuteScalar();
if(executedResult != null) {
result = executedResult.ToString();
}
Hope helps,
Probably the simplest solution would be (assuming query always return result):
string result = com.ExecuteScalar().ToString();
You can cast as nvarchar in your query also:
string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = #Email AND Password = #Password";
Below are my findings
string userID;
using(SqlConnection conn = new SqlConnection(connectionString))
{
string insertQuery = "SELECT UserID FROM Customers WHERE Email = #Email AND
Password = #Password";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Email", tbEmail.Text.ToString().Trim());
com.Parameters.AddWithValue("#Password", tbPassword.Text.ToString().Trim());
SqlDataReader reader = com.ExecuteReader();
while(reader.Read())
{
userID = reader["UserID"].ToString();
}
}
Related
I have database with table tbl_employee. In the table I store usernames. I use the following code to save all the usernames into a List:
string name = txtUsername.Text;
List<string> lst = new List<string>();
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=db;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT username FROM tbl_employee";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
lst.Add(dr.GetString(0));
}
Now, my question is how can I search through my list (lst) to see if the users input from textbox (name) exists in the list?
I have tried this:
if (lst.FindString(name))
//Says it has some invalid arguments
And this:
if (lst.Exists(element => element == name))
//It says name exists even though it doesn't
You could just use Contains:
if (lst.Contains(name)) ...
But if this is all you're doing with the list, I'd recommend changing this code so it queries the tbl_empoyee table directly from the database. I'm not familiar with the NpgsqlCommand but it should look a bit like this:
bool result = false;
string sql = "SELECT username FROM tbl_employee WHERE username = :name";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("name", name);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
result = true; // record found
}
Or like this (following Tim Schmelter's suggestion):
string sql = "SELECT COUNT(*) FROM tbl_employee WHERE username = :name";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("name", name);
int found = (int)command.ExecuteScalar(); // 1 = found; 0 = not found
Try using lst.Contains(name).
Thanks quys! I changed it to count, as you suggested. Here is my final code:
string name = txtUsername.Text;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=db;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT COUNT(*) FROM tbl_employee WHERE username = #val1";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("#val1", name);
var result = command.ExecuteScalar();
int i = Convert.ToInt32(result);
if (i != 0)
{
FormsAuthentication.RedirectFromLoginPage(name, Persist.Checked);
}
else
{
lblMessage.Text = "Invalid username or password";
}
I have the below code, that connects to a Sql database and insert's data into a table :
string firstNameV = txtFname.Text;
string surnameV = txtSname.Text;
string emailV = txtEmail.Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)";
cmd.Parameters.Add("#Title", SqlDbType.NVarChar).Value = title;
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = firstNameV;
cmd.Parameters.Add("#Surname", SqlDbType.NVarChar).Value = surnameV;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = emailV;
cmd.Parameters.Add("#EstablishmentType", SqlDbType.NVarChar).Value = eType;
cmd.Parameters.Add("#Interests", SqlDbType.NVarChar).Value = ins;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
How do I check if an email being entered in the "txtEmail" text box already exists in my database, in the email column and then alert message saying email already exists so it doesn't get inserted into my database?
Call this method in required textbox or area
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Try this
cmd.CommandText = "IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email = '"
+ txtEmail.Text + "')
BEGIN
INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)
END";
Call a stored Procedure and inside the stored procedure you can check
before insert
IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email =#email)
Begin
insert query here
end
In another way you can check it in text changed event also
Create a procedure on SQL server and check whether the name exists or not
CREATE PROCEDURE Procedure_Name
#mystring varchar(100),
#isExist bit out
AS
BEGIN
if exists(select column1 from tblTable1 where column1=#mystring)
begin
select #isExist=1
end
else
begin
select #isExist=0
end
END
GO
This is a sample procedure. If #isExist=1 that means the value exist.otherwise not. create a method to call this procedure and go on...
Happy Coding
This works for me:
Create a function Called CheckMail(string email)
public bool CheckMail(string email)
{
SqlConnection con = new SqlConnection("Data Source=*******; Initial Catalog=Your Database Name; Persist Security Info=True;User ID=****; Password=******");
SqlCommand cmd = new SqlCommand("select email from Table Name where email='"+email+ "'",con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
return false;
}
else
{
return true;
}
}
Then Implement in Button Click as
Pass Textbox value in function that were created..
if (CheckMail(EmailTxt.Text))
{
Write Your insert code to database
}
else
{
Error Message or Alert to Show Already Exists in database
}
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);
does anyone know how do I get the StudentID from Students table, store it in datareader or dataset, and then use it to update another table, which is Users Table, because I want the username and password of users would be their StudentID as a default. BTW, this is C# ASP.NET.
Here is my code.
SqlConnection conUpdate = new SqlConnection(GetConnectionString());
conUpdate.Open();
SqlCommand com2 = new SqlCommand();
com2.Connection = conUpdate;
com2.CommandText = "SELECT Students.StudentID, Users.UserID FROM Students, Users " +
"WHERE Students.UserID = Users.UserID";
int UserId = ((int)com2.ExecuteScalar());
com2.CommandText = "SELECT MAX(StudentID) FROM Students";
int StudentId = ((int)com2.ExecuteScalar());
com2.CommandType = CommandType.Text;
com2.CommandText = "UPDATE Users SET UserName=#UserName, Password=#Password WHERE UserID=#UserID";
com2.Parameters.Add("#UserName", SqlDbType.NVarChar);
com2.Parameters.Add("#Password", SqlDbType.NVarChar);
com2.Parameters[0].Value = reader;
com2.Parameters[1].Value = reader;
com2.ExecuteNonQuery();
conUpdate.Close();
conUpdate.Dispose();
Since you already getting UserId in your select query, you should get the value using DataReader. like this:
// Execute the query
SqlDataReader rdr = cmd.ExecuteReader();
int UserId;
while(rdr.Read())
{
UserId = Convert.ToInt32(rdr["UserID"].ToString());
}
Your command com2.CommandText = "SELECT MAX(StudentID) FROM Students"; will return the Max student ID, and that is probably not needed. Your earlier command com2.CommandText = "SELECT Students.StudentID, Users.UserID .... is what you need to get the student UserID.
You can use Data reader (Connection oriented) like below:
SqlDataReader reader = com2.ExecuteReader();
while (reader.Read())
{
int UserId = Convert.ToInt(reader[0]);// or reader["UserID"]
}
reader.Close();
Or you can use DataAdapter (disconnected mode) like:
SqlDataAdapter a = new SqlDataAdapter(com2, connection);
DataTable dt = new DataTable();
a.Fill(dt);
Now your dt.Rows["UserID"] will have the UserID you need.
You may wanna see this: http://www.dotnetperls.com/sqldataadapter
If I understood you correctly, I think the following code might work. Or in the least give you an idea about how you can go about it. Am assuming that you want each student's UserName and Password to default to their StudentID
SqlConnection conUpdate = new SqlConnection(GetConnectionString());
conUpdate.Open();
SqlCommand com2 = new SqlCommand();
com2.Connection = conUpdate;
com2.CommandType = CommandType.Text;
com2.CommandText = "SELECT Students.StudentID, Users.UserID FROM Students, Users " +
"WHERE Students.UserID = Users.UserID";
SqlDataReader reader = com2.ExecuteReader();
if(reader != null)
{
while(reader.Read())
{
SqlCommand com3 = new SqlCommand();
com3.Connection = conUpdate;
com3.CommandType = CommandType.Text;
com3.CommandText = "UPDATE Users SET UserName=#UserName, Password=#Password WHERE UserID=#UserID";
// Assuming that you need both the UserName and Password to default to StudentID
com3.Parameters.AddWithValue("#UserName", reader.GetString(0)); // Assuming StudentID is NVARCHAR
com3.Parameters.AddWithValue("#Password", reader.GetString(0)); // Assuming StudentID is NVARCHAR
com3.Parameters.AddWithValue("#UserID", reader.GetString(1)); // Assuming UserID is NVARCHAR
com3.ExecuteNonQuery();
}
reader.Close();
}
conUpdate.Close();
I want to assign my variable [vPrenom_id_obtenu] by the value that I get in my MySql DB ...
With the following code, I receive an error message :
does not contain a definition for 'ExecuteScalar' ....
string vFistNam_id_get;
string connDataBaseStr = "server=myserver;user=####;database=myDataBase;port=3306;password=dsdfsdfsdf123;";
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
vFistNam_id_get = (string)connDataBase.ExecuteScalar();
connDataBase.Close();
How can I retrieve the value that is in "column_fistname_id"?
The type of two columns of my table
Le type de deux colonnes de ma table [column_fistname_id] and [column_famillyname] is «text'.
ExecuteScalar is a method to call on an instance of a MySqlCommand not of a MySqlConnection
The right way to go is:
using(MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr))
{
connDataBase.Open();
MySqlCommand cmd = new MySqlCommand(sqlDataBaseSelect, connDataBase);
vFistNam_id_get = (string)cmd.ExecuteScalar();
}
However your code is wrong for another reason.
this sql string
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname='" + vFamillyName + "'";
leads the way to SqlInjection
You should rewrite it in this way
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname=?family";
and then before calling ExecuteScalar add a Parameter to the command
cmd.Parameters.AddWithValue("?family", vFamillyName);
And as added value you don't have to worry about datatype delimiter (single quote in this case)
You need to use MySqlCommand to use ExecuteScalar. You're also missing the SQL in your source code, i.e. select * from something, or a stored proc name.
public static int GetNumRows(String OrchardName)
{
// Create Connection
MySqlConnection con = new MySqlConnection(_connectionString);
// Create Command
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT COUNT(*) FROM orchards WHERE OrchardName = #OrchardName";
cmd.Parameters.Add("#OrchardName", OrchardName);
// Return Count
con.Open();
Int32 NumRows = (Int32)cmd.ExecuteScalar();
return NumRows;
}
Example:
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlDataReader reader = command.ExecuteReader();
string vFistNam_id_get = null;
while (reader.Read())
{
vFistNam_id_get = (int)reader["column_fistname_id"];
}
You're using the ADO.NET types wrong. The easiest thing to do would be to use the MySqlHelper static methods, like this:
string vFistNam_id_get = (string)
MySqlHelper.ExecuteScalar(dbConnString, "select `col1` from `table1`");