I have created one method in data Access class to select data from database with parameter. I just want to use parameterized query.
Method Is :
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
return null;
}
finally
{
myCommand.Connection = CloseConnection();
}
return dataTable;
}
but I can't understand how to use this method to fetch data and how to pass parameter?
My query may be "select password from tblUsers where email=#email" How to pass #email at business layer?
How to make method in data access class for getting Scalar value?
public string getpasswrd(string unm)
{
con.Open();
string cpaswrd;
cmd1 = new SqlCommand("select password from tbl_login where username='" + unm + "'", con);
cpaswrd = (String)cmd1.ExecuteScalar();
con.Close();
return cpaswrd;
}
SqlParameter param;
cmd1 = new SqlCommand("select password from tbl_login where username=#username, con);
param = new SqlParameter("#username", SqlDbType.VarChar);
param.Direction = ParameterDirection.Input;
param.Value = unm;
cmd1.Parameters.Add(param);
cpaswrd = cmd1.ExecuteScalar().ToString();
You just need to use the same name in the sql parameter:
new SqlParameter("email", "myemail#gmail.com")
Related
I have a method in DataBase class that resides in App_Code which I use to call a Stored Procedure for Login, but when I make the call I get no error but my Login will not complete.
This is the DataBase Class:
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
}
public DataTable CallSP(string UserName, string Password)
{
con = new SqlConnection(#"Data Source=MyServer;Initial Catalog=MyDataBase;Integrated Security=True");
con.Open();
cmd = new SqlCommand("LoginUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = "UserName";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 20).Value = "Password";
da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
return dt;
}
This is the code I used to call for Login:
DataBaseClass dbClass = new DataBaseClass();
dt = new DataTable();
dt = dbClass.CallSP("UserName", "Password");
if (dt.Rows.Count > 0)
{
boolReturnValue = true;
Session["UserId"] = dt.Rows[0]["Id"].ToString();
string updateLastLogin = "Update [User] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["UserId"].ToString() + "'";
dbClass.ConnectDataBaseToInsert(updateLastLogin);
}
return boolReturnValue;
}
This is My Stored Procedure:
CREATE PROCEDURE [dbo].[LoginUser] (
#UserName nvarchar(20),
#Password nvarchar(20)
)
AS
SET NOCOUNT ON;
(
SELECT * FROM [User] WHERE Email = #UserName AND Password = #Password
)
Can anyone reproduce my code and tell me why my Login call could not work.
Try do the following changes in the CallSP method:
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = UserName;
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 20).Value = Password;
Now appling more attention in your code I saw that your parameters are around quotes, so you were passing the literal strings "UserName" and "Password" instead the values.
With this changes you will pass the values from your parameters.
Sorry by my mistakes.
I hope it can help you.
I am new to ASP.NET C#, I am working to develop web forms to send and receive messages (SQL Server as database) like emails. I want to store the result of SQL query in Session Variable and use it later in another page.
Kindly help me how can I do that, please correct if any things goes wrong.
Here is my code:
SqlConnection con = new SqlConnection("Data Source=AZEEM\\SQLEXPRESS; Initial Catalog=kics;User ID=sa;Password=123");
con.Open();
String query = "select username as sender,subject,message from emailtable where receiver='" + Session["username"] + "'";
enter code here
//this is the query for which I want to store the result in variable myvar, how can I store the result of following query in variable myvar and use it later, when I execute it, string is shown instead of result of string.
String myvar = "select receiver from emailtable where username='" + Session["username"] + "'";
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(query, con);
SqlCommand cmd2 = new SqlCommand(myvar, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
reader = cmd2.ExecuteReader();
GridView1.DataSource = dt;
GridView1.DataBind();
DataSet ds = new DataSet();
ds = myvar;
Try below,
SqlConnection con = new SqlConnection("Data Source=AZEEM\\SQLEXPRESS; Initial Catalog=kics;User ID=sa;Password=123");
con.Open();
String query = "select username as sender,subject,message from emailtable where receiver='" + Session["username"] + "'";
enter code here
//this is the query for which I want to store the result in variable myvar, how can I store the result of following query in variable myvar and use it later, when I execute it, string is shown instead of result of string.
String myvar = "select receiver from emailtable where username='" + Session["username"] + "'";
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(query, con);
SqlCommand cmd2 = new SqlCommand(myvar, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
reader = cmd2.ExecuteReader();
GridView1.DataSource = dt;
GridView1.DataBind();
session["dt"] = dt;
When you retrieve,
if (session["dt"] != null) {
DataTable dt = (DataTable)session["dt"];
}
You Need to Pass that Query to this Method which will return you the result Set and then try to assign it to the Session
String myvar = "select receiver from emailtable where username='" + Session["username"] + "'";
Session["myvar"] = GetData(myvar);
Method for GetData as Follows
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = "Data Source=AZEEM\\SQLEXPRESS; Initial Catalog=kics;User ID=sa;Password=123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
I have the following code:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=#username and Password=#password and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Here I want to fetch some values from the table according to a condition,
but when I run this code it shows the following error:
Even though I passed the correct parameters value in #username and #password. How can I resolve this error? Please help.
Try This:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=? and Password=? and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Try This
string query = "Select [UserId],[Firstname],[UserType] from [TBL_USER_LOGIN] where [Username]=? and [Password]=? and [Status]=1";
The parameters aren't add to the sql string, what i'm doing wrong?
SqlCommand comando = conexao.CreateCommand();
comando.CommandTimeout = 7200;
foreach (SqlParameter parametro in parametros)
{
comando.Parameters.Add(new SqlParameter(parametro.ParameterName, parametro.Value));
}
comando.CommandText = cmdSql;
comando.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = comando;
try
{
adapter.Fill(dt);
}
catch (Exception ex) { Console.Write(ex.Message); }
conexao.Close();
return dt;
The Sql String, with the method who call the method above.
string cmdSql = "select top #quantidade * from representante";
SqlParameterCollection sqlParameters = new SqlCommand().Parameters;
sqlParameters.AddWithValue("#quantidade", SqlDbType.Int).Value = quantidade;
return Persistencia.Persistencia.ConsultaComando(cmdSql, sqlParameters);
Thanks for all helping but the solution is use string cmdSql = "select top (#quantidade) * from representante"; was answered in the MSDN:
Answer in MSDN BRASIL
Assign CommandText before adding parameters and show cmdSql content.
On the AddWithValue method you are trying to pass an enum as the parameter value.
Replace this:
sqlParameters.AddWithValue("#quantidade", SqlDbType.Int).Value = quantidade;
With this:
sqlParameters.AddWithValue("#quantidade", quantidade);
I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable
body of procedure
select * from table
end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}