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";
}
Related
I have a user login menu. I want to redirect the user based on their Level. The Level data is in the SQL table. I want to get the Level data from the table based on their username and assign it to a variable.
protected void btnDefault_Click(object sender, EventArgs e)
{
//filter entered text
string strUserName = Tools.checkSQLInjection(txtUserName.Text).Trim();
string strPassword = Tools.checkSQLInjection(txtPassword.Text);
string strError = "";
//Get Dealer Level Value
SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email='" + strUserName + "'");
string strDealerLvl = "dealerLvl".ToString();
int intDealerLvl;
bool isParsable = Int32.TryParse(strDealerLvl, out intDealerLvl);
if (strDealerLvl == "1")
{ Response.Redirect("/dealers/dashboard"); }
else if (strDealerLvl == "2")
{ Response.Redirect("/dealers/dashboard-2"); }
You don't seem to be checking the password, but perhaps that supposed to come later.
A working code stub to do this would look like say this:
DataTable MyTable = new DataTable();
int intDealerLvl = 0;
using (SqlCommand cmdSQL = new SqlCommand("SELECT dealerLv1 FROM Users where email = #meail",
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
}
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
switch (intDealerLvl)
{
case 1:
{
Response.Redirect("/dealers/dashboard");
break;
}
case 2:
{
Response.Redirect("/dealers/dashboard-2");
break;
}
default:
{
// no level found - where to go??
break;
}
}
However, it not clear if you supposed to be checking the password, and if so then of course we use this:
DataTable MyTable = new DataTable();
string strSQL;
strSQL = "SELECT dealerLv1 FROM Users where email = #Email and Password = #Pass";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Parameters.Add("#Pass", SqlDbType.NVarChar).Value = strPassword;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
using(SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email= #strUserName", connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#strUserName", strUserName);
DataSet ds = new DataSet();
using(SqlDataAdapter da = new SqlDataAdapter(command))
da.Fill(ds);
//Get the result of the first row
DataRow dr = ds.Tables[0].Rows[0];
//Get the value of the column in the first row
string strDealerLvl = dr["dealerLvl"].ToString();
}
public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
My visitorcompany class:
public int checksamecompanyname(ref DataSet result, string Location1)
{
string strConn = Convert.ToString(
ConfigurationManager.ConnectionStrings
["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand
("select Companyname from tblVisitorcompany where Location1 ='" + Location1 + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(result, "details");
conn.Close();
//Return 0 when no error occurs.
return 0;
}
I am trying to search one row at a time to check whether the sql table got the same companyname. if there is already exisiting companyname, the program will do nothing. If this is a new companyname, the program will add companyname into the sql table. However, when adding new companyname, the program will add more than once. Can someone please help me to re-edit my program such that it only add one new companyname. Many thanks.
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}
dont use companyname as an argument of your insert command, since it is stays the same in for loop. Use result.Tables["details"].Rows[i]["Companyname"].ToString() instead:
...
cmd.Parameters.AddWithValue("#Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
Check if the value exists, then add it if not.
A simple change in your code:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Off course you could check if the value exists in a more efficient way, but this should at least solve your specific problem.
I am creating a login system but I dont know how to handle the login information (username and password)
Here is my code:
MySqlConnection connection = new MySqlConnection(MySQLConnection);
connection.Open();
string result = string.Empty;
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM users WHERE nick="+nick.Text+" AND password="+pass.Text+" LIMIT 1;";
MySqlDataReader dataReader = cmd.ExecuteReader();
result = (string)cmd.ExecuteScalar();
connection.Close();
if (result.Length!=0)
{
int id;
label3.Text = "Loged.";
dataReader.Read();
id = Convert.ToInt32(dataReader[0]);
game g = new game();
g.label1.Text = Convert.ToString(dataReader[1]);
g.label84.Text = Convert.ToString(id);
this.Hide();
g.Show();
}
else
{
label3.Text = "Bad information.";
}
This doesnt work: how do I check if the user exists with this information(username and password) and that the details are valid?
Following should be done:
Use Parameterized Query and using statement
Use only MySqlDataReader no need of ExecuteScalar
Check if dataReader.HasRows
Read values from reader and perform required action.
Code:
using (MySqlConnection connection = new MySqlConnection(MySQLConnection))
{
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM users WHERE nick=#nick AND password=#pass LIMIT 1;";
cmd.Parameters.AddWithValue("#nick", nick.Text);
cmd.Parameters.AddWithValue("#pass", pass.Text);
using (MySqlDataReader dataReader = cmd.ExecuteReader())
{
if (dataReader.HasRows)
{
label3.Text = "Loged.";
dataReader.Read();
int id = Convert.ToInt32(dataReader[0]);
game g = new game();
g.label1.Text = Convert.ToString(dataReader[1]);
g.label84.Text = id.ToString();
this.Hide();
g.Show();
}
else
{
label3.Text = "Bad information.";
}
}
}
I think the problem is your select statement. You have to use single quote in where condition for the string data types
Try the following query
cmd.CommandText = "SELECT * FROM users WHERE nick='"+nick.Text+"' AND password='"+pass.Text+"' LIMIT 1;";
Also you can make the query parameterized, which is more efficient.
I ran the SQL Query in SQL Server Management Studio and it worked.
I get the following error in my WinForm C# application
The parameterized query '(#word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '#word1', which was not supplied.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
The error is happening on da.Fill(dt)
Any suggestions would be helpful
Thank you
In your example, you have commented out the line where you set the value of the Parameter:
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
If you do not set a value for a parameter, it is ignored (and won't exist).
Change to this:
command.Parameters.AddWithValue(name, word);
For clarity, consider this quote:
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
From here: SqlParameterCollection.AddWithValue Method
On var name = "#word" + (i++).ToString(); use just i, increment somewhere else.
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();