c# ado.net sqlparameter fails - c#

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();

Related

Trying to pass SqlCommand in SqlDataAdapter as parameters

I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.

How do I get last input to column (ID)

I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.

not all code paths return a value c# - private string and for loop

Hi before you mark this as a duplicate I have looked and tried others and had no luck. I keep getting the error for the string getBrand saying that:
not all code paths return a value.
private string getBrand(string id)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select brand from tbl_products where productId = '" + id + "'";
cmd.ExecuteNonQuery();
con.Close();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
getBrand = dt.Rows[0][0].ToString();
}
Below is where I get the string 'id' that pass to the getBrand String wish the run the query from.
for (int i = 0; i < salesGridView.Rows.Count; i++)
{
table2.AddCell(new Phrase(salesGridView[1, i].Value.ToString(), normFont));
string id = salesGridView[0, i].Value.ToString();
table2.AddCell(new Phrase(getBrand(id), normFont));
}
You've stored the dt.Rows[0][0].ToString(); into the method's name. You need to return the following line from your method:
return dt.Rows[0][0].ToString();
Or store it in a different variable's name and then return that variable. Like this:
var temp = dt.Rows[0][0].ToString();
return temp;
You should do it this way:
private string getBrand(string id)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select brand from tbl_products where productId = '" + id + "'";
cmd.ExecuteNonQuery();
con.Close();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
return dt.Rows[0][0].ToString();
}

how two get data from 2 different table c#

I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();

Struggling to populate datagrid from stored procedure with parameters

protected DataTable RetrieveAlumni2()
{
{
MySqlConnection con = new MySqlConnection("server=100.0.0.0;user id=id;password=pass;database=db;persistsecurityinfo=True");
MySqlCommand cmd = new MySqlCommand("get_alumni_by_city", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
string city = textBox1.Text;
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#city", SqlDbType.VarChar).Value = city;
da.SelectCommand = cmd;
cmd.ExecuteNonQuery();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cmd.Dispose();
con.Close();
}
return dt;
}
}
Giving error:
"input string was not in a correct format"
City is varchar in the mysql server. Any help would be appreciated.
Have you tried just this?
cmd.Parameters.AddWithValue("#city","" + city + "");
Check the type of #city in your stored procedure. If it doesn't match what your throwing in, it will reject it.

Categories

Resources