Issue with database connect - database

In this section I get the error
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
try
{
SqlCommand cmd = new SqlCommand("delete from sug where IDbro='" + ime + "'and AtributValue='+atr+' and [+/-]='+rat+' ", conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
finally
{
conn.Close();
}
GridView2.DataBind();
promenaP();
}
I have issue with database deleting error exception

Try this
SqlCommand cmd = new SqlCommand("delete from sug where IDbro='" + ime + "'and AtributValue='"+atr+"' and [+/-]='"+rat+"' ", conn);
add ""
I had similar issue programming android sqlite...

Related

Login for users of different positions

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.

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll in Winform

I'm using SQL Server 2014 and this is my code:
void loadProductsInfor()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"server=.\SQLEXPRESS;database=CNET_Block3;uid=sa;pwd=123456;integrated security=true";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Products";
SqlDataReader dr = cmd.ExecuteReader(); // Exception happens here
while (dr.Read())
{
dataGridView1.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString(), dr[6].ToString(), dr[7].ToString(), dr[8].ToString(), dr[9].ToString(), dr[10].ToString());
}
dr.Close();
con.Close();
}
I tried many things but they didn't work.

Database entry not done

try
{
// Data Source=FAHAD-PC\SQLEXPRESS;Initial Catalog="Student management";Integrated Security=True
// server=FAHAD-PC\\SQLEXPRESS;database=Student management;
String str = "Data Source=FAHAD-PC\\SQLEXPRESS;Initial Catalog=Student management;Integrated Security=True;";
String query = "Insert into Users (Username, Password) values('usern' , 'userpassword');";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataSet ds = new DataSet();
MessageBox.Show("connect with sql server");
con.Close();
MessageBox.Show("Inserted sucessfully");
usern = " ";
userpassword = " ";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
here is the code my connection is successfull and the query insterted msg is also show but cant get the entry in my db.
Try code below
try
{
// Data Source=FAHAD-PC\SQLEXPRESS;Initial Catalog="Student management";Integrated Security=True
// server=FAHAD-PC\\SQLEXPRESS;database=Student management;
String str = "Data Source=FAHAD-PC\\SQLEXPRESS;Initial Catalog=Student management;Integrated Security=True;";
String query = "Insert into Users (Username, Password) values('usern' , 'userpassword');";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("connect with sql server");
con.Close();
MessageBox.Show("Inserted sucessfully");
usern = " ";
userpassword = " ";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

Error in Win Form Login

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.

Stored procedure couldn't be reached

The stored procedure cannot be executed. Can anyone please advise me and point out my stupid mistake?
The error message that I got is
Invalid operation. The connection is closed
Code:
public void Update(RepliesBAL RPBAL)
{
using (SqlConnection connection = new SqlConnection(#"Data Source=19NNZP;Initial Catalog=ivr;Persist Security Info=True;User ID=sa;Password=sa"))
{
SqlCommand command = new SqlCommand ();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.fax_UpdateFaxReply";
command.Parameters.Add("#uid", SqlDbType.VarChar, 50).Value = RPBAL.UlyssesID ;
SqlTransaction transaction;
transaction = connection.BeginTransaction("SampleTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
throw new Exception(ex.Message);
}
}
}
}
In order to call .BeginTransaction(), your connection needs to be opened already - so change your code to:
using (SqlConnection connection = new SqlConnection(#"Data Source=19NNZP;Initial Catalog=ivr;Persist Security Info=True;User ID=sa;Password=sa"))
{
// set up the SqlCommand
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.fax_UpdateFaxReply";
// SqlDbType should be *NVarChar* to exactly match the stored procedure parameter's type!
// Otherwise you'll have an implicit conversion happening....
command.Parameters.Add("#uid", SqlDbType.NVarChar, 50).Value = RPBAL.UlyssesID ;
SqlTransaction transaction;
try
{
// open connection, start transaction
connection.Open();
transaction = connection.BeginTransaction("SampleTransaction");
// assign transaction to SqlCommand and execute it
command.Transaction = transaction;
command.ExecuteNonQuery();
// if successful - commit the transaction!
transaction.Commit();
connection.Close();
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
throw new Exception(ex.Message);
}
}
}
After that change, hopefully, this code should work just fine.

Resources