I don't understand it. This code should work, but there must be something I've done wrong.
Can anyone see what I've done wrong?
string username = tbNewUSER.Text.Trim();
string password = tbNewPass.Text.Trim();
string role = "USER";
string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values ('" + username + "','" + password + "','" + role + "')";
MessageBox.Show(username + " Registered", "User registration",MessageBoxButtons.OK, MessageBoxIcon.Information);
clsDB.InsUpDel(str);
And this is the follow up:
public static int InsUpDel(string str)
{
if (!(conn.State == ConnectionState.Open))
conn.Open(); //open connection if closed
int numRows = 0; //counter that checks number of rows affected in the db
try
{
SqlCommand cmd = new SqlCommand(str, conn);
numRows = cmd.ExecuteNonQuery();
cmd = null;
}
catch (SqlException ex)
{
string errorMsg = ex.Message; //more code can be put here
}
if (conn.State == ConnectionState.Open)
conn.Close();
return numRows;
}
Thank you.
Side notes:
Always use parameters for your queries and never string concatenation. For fun see Bobby Tables
Do not use static, there are not many places you need this.
Dont share database connections, create them and destroy them as needed.
Do not store passwords as plain text ever!
Do not catch exceptions you do not plan to handle. Log them and rethrow (using throw;) or do not catch at all. This last one will help you figure out why "its not working"
Updated code
public void UpdateUser() {
var userModel = new UserModel {
Username = tbNewUSER.Text.Trim(),
Password = tbNewPass.Text.Trim(),
Role = "USER"
};
var result = UpdateUser(userModel);
}
public int UpdateUser(UserModel user)
{
const string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values (#userName, #password, #role)";
using(var conn = new SqlConnection("your connection string here, hint best to get it from the app.config"))
using(var command = new SqlCommand(str, conn))
{
command.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 255) {Value = user.UserName});
command.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar, 255) {Value = user.Password});
command.Parameters.Add(new SqlParameter("#role", SqlDbType.VarChar, 255) {Value = user.Role});
conn.Open();
return cmd.ExecuteNonQuery();
}
}
UserModel.cs
public class UserModel {
public string UserName {get;set;}
public string Password {get;set;}
public string Role {get;set;}
}
Related
So i have a function for when clicking the button, the application would get the username and password stored in a table in oracle, and then compare it to the values entered in the textbox.
My question is that, instead of getting the values from the pre-created table, can i get the values from the DBA_USERS table, since the password is hashed?
Here's the code that fetch data from a created table:
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=localhost:1522/ORCL;DBA Privilege=SYSDBA;User Id=sys;Password=123456;";
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
OracleCommand cmd1 = new OracleCommand();
OracleParameter parm = new OracleParameter();
OracleParameter parm1 = new OracleParameter();
parm.OracleDbType = OracleDbType.Int64;
cmd.Connection = conn;
cmd.CommandText = "Select * from Users";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
if (textBox1.Text.Equals(dr["username"].ToString()) && textBox2.Text.Equals(dr["password"].ToString()))
{
MessageBox.Show("Successful", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
var menu = new Menu();
menu.Show();
this.Hide();
}
}
}
How can I attach a password protected sqlite database to a non password protected database?
I have a user sqlite database that is not password protected.
I'm trying to attach a read-only resource database that is password protected.
I could reverse their roles and open the password protected first and attach the user database, but I think it should work this way?
I haven't tried too many things so there is no code to share. but I have googled and can't seem to find any mention of this in the documentation or any examples.
It's all about opening a password protected database directly.
Edit: - heres what i've tried...
using both https://www.sqlite.org/lang_attach.html https://www.sqlite.org/c3ref/open.html
private void btnPasswordAttach_Click(object sender, EventArgs e)
{
string pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Users #1.astc";
string connectionstring = string.Format("Data Source={0};Version=3;BinaryGUID=false", pathToUnProtected);
SQLiteConnection connection = new SQLiteConnection(connectionstring);
connection.Open();
TestQueryMain(connection); **//WORKS**
pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Mods #1.aste";
string commandTextUnProtected = string.Format("ATTACH DATABASE '{0}' AS mods", pathToUnProtected);
SQLiteCommand attachCommandUnProtected = new SQLiteCommand(commandTextUnProtected, connection);
attachCommandUnProtected.ExecuteNonQuery();
TestQueryUnProtected(connection); **//WORKS**
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite";
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
//string pathToProtected = #"file:C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite;password=VanillaIceCream;";
string password = "VanillaIceCream";
string commandText = string.Format("ATTACH DATABASE '{0}' AS vanilla", pathToProtected);
SQLiteCommand attachCommandProtected = new SQLiteCommand(commandText, connection);
attachCommandProtected.ExecuteNonQuery();
TestQueryProtected(connection); **//NO SUCH TABLE...**
}
private void TestQueryMain(SQLiteConnection connection)
{
string sql = "Select * FROM Notes";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteReader();
}
private void TestQueryProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from vanilla.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
private void TestQueryUnProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from mods.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
found the answer in another post:
https://stackoverflow.com/a/1385690/10099912
to attach a password protected sqlite database you need to use the 'key'word:
"ATTACH DATABASE 'C:\test.sqlite' AS attachedDb KEY 'password'"
I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.
private void Button1Click(object sender, EventArgs e)
{
var dt = new DataTable();
const string Connectionstring = "Data Source=GARETH-PC1;Initial Catalog=Genres;Integrated Security=True";
using (var con = new SqlConnection(Connectionstring))
{
con.Open();
var query = "Select Username From Login Where Username ='" + ComboBox1.SelectedText + "' Password ='" + textBox2.Text + "'";
using (var sda = new SqlDataAdapter(query, con))
{
sda.Fill(dt);
}
}
if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1")
{
Hide();
var ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
The if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1") - Returns an error saying there's nothing in the table... But there is ..any suggestions?
Maybe you can try like this:
dt.Rows[0]["ColumnName"].ToString()
This is working for me.
I would change your code in this way.
First, change to a parameterized query instead of a string concatenation (Sql Injection and parsing)
Second, use the count property to check if you have found a record or not
private void Button1Click(object sender, EventArgs e)
{
var dt = new DataTable();
const string Connectionstring = "Data Source=GARETH-PC1;Initial Catalog=Genres;Integrated Security=True";
var query = "Select Username From Login Where Username =#uname AND Password=#pwd";
using (var con = new SqlConnection(Connectionstring))
using (var cmd = new SqlCommand(query, con)
{
con.Open();
cmd.Parameters.AddWithValue("#uname", ComboBox1.SelectedText);
cmd.Parameters.AddWithValue("#pwd", textBox2.Text);
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Hide();
var ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
As a side note, it is a very bad idea to store passwords in plain text inside a database. You should consider to use an HASH and store it instead of the plain password.
I'm trying to read an image from a SQL Server database, but I'm get an error:
Parameter is not valid
Who can help me? How to fix it?
byte[] im = connection.ReadImg(id);
if (im != null)
{
MemoryStream st1 = new MemoryStream(im);
pictureBox1.Image = Image.FromStream(st1);
}
else
pictureBox1.Image = Image.FromFile(fn);
public byte[] ReadImg(string id)
{
cmd.Connection = con;
cmd.CommandText = "SELECT photo FROM User WHERE id=" + id;
byte[] image = null;
con.Open();
try
{
image = (byte[])cmd.ExecuteScalar();
}
catch
{
image = null;
}
con.Close();
return image;
}
If id is a string, you have to pass it as a string:
cmd.CommandText = "SELECT photo FROM User WHERE id=#id";
cmd.Parameters.AddWithValue("#id", id);
If not using the recommended parameter way, the problem is you need to have the string parameter enclosed in single quotes:
cmd.CommandText = "SELECT photo FROM User WHERE id='" + id + "'";
This is considered bad practice.
The SELECT statement does not return a scalar; you need to use ExecuteReader or similar;
SqlDataReader reader = cmd.ExecuteReader();
using(reader)
{
while(reader.Read())
{
// Do something with reader["photo"].
}
}
To provide more we need the data types of id and photo.