Fail to fill datatable using data adapter - c#

i'm try to match the data with the database and using dataadapter to fill my datatable. if matched, fill the datatable with dataadapter. if not match, show msg. but my username and password is matched with database, it still show msg. under debug mode, username and password is all pass through but not fill in the datatable.
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = connStr;
conn.Open();
string sql = #"select user_id, password, status, role_id, email, contact_no,
last_login_date, created_by, last_update_date, last_update_by
from users where user_id = :userID and password = :pwd";
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameters.Add("userID", OracleType.VarChar).Value = userID;
cmd.Parameters.Add("pwd", OracleType.VarChar).Value = pwd;
DataTable dt = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
adapter.Fill(dt);
if (dt.Rows.Count <= 0)
{
msg = "Invalid Login ID or Password";
}
return dt;
}
}
the dt.Rows.Count is 0. but I checked username and password is exactly same with the database.

SQL:
create procedure sp_authenticate
(
#userId varchar(50),
#pass varchar(50)
)
as
begin
select user_id, password, status, role_id, email, contact_no,
last_login_date, created_by, last_update_date, last_update_by
from users where user_id = #userid and password = #pass
end
C# code:
using (OracaleConnection con=new OracaleConnection())
{
conn.ConnectionString = connStr;
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = "sp_authenticate"; //name of your procedure
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userid", OracleType.VarChar,50).value=userID;
cmd.Parameters.Add("#password", OracleType.VarChar,50).value=pwd;
DataTable dt = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
adapter.Fill(dt);
if (dt.Rows.Count <= 0)
{
msg = "Invalid Login ID or Password"; }
}
return dt;
}

Related

Double data in database

[WebMethod]
public string Login(string Username, string Password)
{
String result;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Nicole Wong\Desktop\Inari Tracking System\Inari Tracking System\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Username, Password from UserData where Username = #Username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#UserName", Username);
cmd.Parameters.AddWithValue("#Password", Password);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count> 0)
{
DateTime dt = DateTime.Now;
SqlCommand cmd1 = new SqlCommand("INSERT INTO ActivityLog (CreateOn, CreateBy) VALUES (#CreateOn,#CreateBy)", con);
cmd1.Parameters.AddWithValue("#CreateOn", dt);
cmd1.Parameters.AddWithValue("#CreateBy", Username);
cmd1.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
// Create an instance of DataSet.
DataSet ds1 = new DataSet();
da1.Fill(ds);
con.Close();
result = "Successful";
return result;
}
else
{
result = "Fail";
return result;
}
This is my simple web method to store user login time into database.
The problem is the data saved twice into the database. For example, I login into the system, then it returns successful, but I checked the database there is two same records saved with the same data. I run with breakpoint but the there is no any duplication, the code run nicely line by line.
Any idea? Thank you in advance
public string Login(string Username, string Password)
{
String result;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Nicole Wong\Desktop\Inari Tracking System\Inari Tracking System\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Username, Password from UserData where Username = #Username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#UserName", Username);
cmd.Parameters.AddWithValue("#Password", Password);
//This us pretty much useless on a select, SELECT is a query, not a NonQuery
//cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count> 0)
{
DateTime dt = DateTime.Now;
SqlCommand cmd1 = new SqlCommand("INSERT INTO ActivityLog (CreateOn, CreateBy) VALUES (#CreateOn,#CreateBy)", con);
cmd1.Parameters.AddWithValue("#CreateOn", dt);
cmd1.Parameters.AddWithValue("#CreateBy", Username);
cmd1.ExecuteNonQuery();
//Don't use the DataAdapter and try to fill a dataset from an insert, all this insert will return is ##ROWCOUNT
//SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
// Create an instance of DataSet.
//DataSet ds1 = new DataSet();
//da1.Fill(ds);
con.Close();
result = "Successful";
return result;
}
else
{
result = "Fail";
return result;
}
You executed both your select and your insert twice, with the select it didn't matter so much, but with the insert it does. Remove the .ExecuteNonQuery() from the select and remove the SqlDataAdapter from the insert.

Checking if user exists in MySQL database fails

Not sure why the following code gives me an exception. I'm trying to check if a username exists in a MySQL database, if not then I want to create a user. If I run either query by itself then it works ok but not together.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
string sql1 = String.Format("SELECT Username FROM Users WHERE Username = \"{0}\"", username);
MySqlCommand cmd1 = new MySqlCommand(sql1, cnn);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
string sql = String.Format("INSERT INTO Users(Username, Password) VALUES(\"{0}\", \"{1}\")", username, password);
MySqlCommand cmd = new MySqlCommand(sql, cnn);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
First, MySQL uses single quotes. This means your query would be:
string.format("SELECT Username FROM Users WHERE Username = '{0}' LIMIT 1", Username);
However, this is very vulnerable with SQL injection. Here's a code to use MySQL Parameters to prevent it.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
cmd1.Parameters.AddWithValue("#username", username);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO Users(Username, Password) VALUES(#username, #password)", cnn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
Could you try this?
I got it working by changing the first query from:
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
to
MySqlCommand cmd1 = new MySqlCommand("SELECT COUNT(UserID) FROM Users WHERE Username = #username", cnn);
int valid = int.Parse(cmd.ExecuteScalar().ToString());
Thanks for the help.

Asp.net Cascading delete into Gridview_Rowdeleting event

I have a problem that to deleting record from database. I want to delete with using Id but it has been exist other tables as foreign key. That's why I need to delete with extension.
I need to delete record from 3 tables which are Conferences, Conferences_Rewivers, Topics.
My codes like that but it throws error because of it doesn't delete records from all tables. How can I fix it?
protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source = ---\\SQLEXPRESS; Initial Catalog = --; Integrated Security = True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete FROM Conferences where Id = #Id";
cmd.Connection = cn;
cmd.Parameters.AddWithValue("#Id", GridView1.DataKeys[e.RowIndex].Value);
cn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Conferences_Rewivers where fk_Conferences = #Id";
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Topics where fk_Conferences = #Id";
cmd.ExecuteNonQuery();
cn.Close();
BindGridView();
}
BindGridView
if(Session["user"] != null)
{
user = Session["user"] as User;
}
SqlCommand cmd = new SqlCommand("select Conferences.Id, Conferences.conferenceName, Conferences.conferenceDate , Conferences.conferencePlace, Conferences.submissionDueDate , Conferences.category, Conferences.status, Conferences.conferenceDescription from Conferences inner join Users on Conferences.fk_Users = Users.Id where Users.Id = #UserId", conn);
SqlParameter prm = cmd.Parameters.AddWithValue("#UserId", user.Id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
if(dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
First you delete foreign key tables(Conferences_Rewivers,Topics) after that you can delete main table(primary key table i.e Conferences)

c# ado.net sqlparameter fails

I am passing sqlparameter in localize language (Persian) from c# but no rows retrieves. Database already collate for persioan_100_ci_ai and tables are collate database_default
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]=#UserName AND [Pwd]=#Password";
cmd.commandtext = qry;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = "ادمین";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = "ادمین";
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
It works in SSMS
declare #UserName nvarchar(50) = 'ادمين'
declare #Password nvarchar(50)= 'ادمين'
select * from Users where [name]=#UserName and [Pwd] = #Password
It even works when I am embedding variables in query instead of parameter
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
string pLoginName = "ادمین";
string pPassword = "ادمین";
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]='" + pLoginName + "' AND [Pwd]='" + pPassword + "'";
cmd.CommandText = qry;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
Cannot figure out where I am wrong.
Please, if any one can point out.
I don't have any problems, I add both values to my test database. Here is the sample code
// Code in BO logic method
string email = "ادمین";
string password = "ادمین";
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Register WHERE Email=#Email AND Deleted=0 AND Password=#Pass");
cmd.Parameters.AddWithValue(#"Email", email.Trim());
cmd.Parameters.AddWithValue(#"Pass", password.Trim());
DataSet dst = Varmebaronen.AppCode.DA.SqlManager.GetDataSet(cmd);
//DataAccess Methods !
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
DataSet had one record, try to use AddWithValue. If again nothing happen the problem is not in the parameters !
P.S Don't use one static connection, application pool is your friend !
Try seperating out the parameter and value assignment like below:
// Create the parameter objects as specific as possible.
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 50);
// Add the parameter values. Validation should have already happened.
cmd.Parameters["#UserName"].Value = "ادمین";
cmd.Parameters["#Password"].Value = "ادمین";
Try to use this:
cmd.Parameters.Add(new SqlParameter("#Password", "ادمین"));
EDIT:
Lets try a different way. If you're up for some re-coding. I will post an example from an old college project that works. It's essentially the same concept. May not be the best way but it works...
I used a DataAdapter, a DataSet, and a GridView control on an .aspx page. You tagged ASP.net, but I am not sure what you're trying to use to display the data.
string selectsql2 = "SELECT * FROM [dbo].Event_View WHERE (EventName LIKE '%' + #EventName + '%')";
SqlConnection connect2 = new SqlConnection(connectionstring2);
SqlCommand cmd = new SqlCommand(selectsql2, connect2);
SqlParameter pm = new SqlParameter("#EventName", txtEvents.Text);
cmd.Parameters.Add(pm);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
gvEvents.DataSource = ds2;
gvEvents.DataBind();

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

Categories

Resources