Here is my code
public string LeaderIdLookup(string leadername)
{
string step = null;
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select EmpId,Fullname from Employee where FullName like '#LeaderName'";
cmd.Parameters.Add(new SqlParameter("LeaderName", SqlDbType.VarChar));
cmd.Parameters["LeaderName"].Value = leadername.Trim();
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
step = "assigning the value from datareader to the variable lookup as a string (leaderidlookup) ";
if (dr.HasRows)
Lookup = dr[0].ToString();
else
Lookup = "no rows found";
dr.Close();
return Lookup;
}
catch (SqlException ex)
{
Lasterror = string.Format("step {0} threw sql error {1}", step, ex.Message);
Debug.Print(Lasterror);
return string.Empty;
}
catch (Exception ex)
{
Lasterror = string.Format("step {0} threw error {1}", step, ex.Message);
Debug.Print(Lasterror);
return string.Empty;
}
}
The problem is that SqlDataReader does not return any rows
I have a hunch that it has to do with the Parameter substitution because when i hardcode a name in there instead of using a parameter it works perfectly
I can not seem to figure out where im going wrong.
You need to remove the quotes around "LIKE '#LeaderName'" and you must specify the parameter name with a leading #. So:
... new SqlParameter("#LeaderName", ...
You need to remove the single quotes around the variable name in the query. Otherwise you are doing a literal compare between FullName and "#LeaderName" ... which is unlikely to exist (the reason you are getting no rows). You will also need to provide the Parameter name with a leading #.
cmd.CommandText = "select EmpId,Fullname from Employee where FullName like #LeaderName";
var leaderParameter = cmd.Parameters.Parameters.Add("#LeaderName", System.Data.SqlDbType.NVarChar);
leaderParameter.Value = "%" + leaderName.Trim() + "%";
Where is your SqlConnection? Try something like shown below.
See here for connection string examples: https://msdn.microsoft.com/en-us/library/ms254500(v=vs.110).aspx#Anchor_2
Your connection string will be something like this: "Data Source=localhost;Initial Catalog=MyDataBaseName;Integrated Security=true" (assuming your are connecting to localhost and your account has privileges on the database of course)
try
{
using (SqlConnection sqlConnection = new SqlConnection("put your connection string here"))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("select EmpId,Fullname from Employee where FullName like #LeaderName", sqlConnection))
{
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Parameters.Add("#LeaderName", SqlDbType.VarChar).Value = leadername;
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
//lots of options here, read it how you like...
string EmpID = sqlDataReader["EmpID"].ToString();
string FullName = sqlDataReader["FullName"].ToString();
}
}
}
}
catch (Exception ex) { throw new System.ArgumentException(ex.Message); }
Related
Good morning, I'm developing a code that can get me out of my database in sql, the AVG of a certain column.
The problem is that I'm not getting it, I think the problem is the query but I do not know how to solve it.
I need help, thank you.
Here is the code:
String connectionString =
"Data Source=localhost;" +
"Initial Catalog=DB_SACC;" +
"User id=sa;" +
"Password=1234;";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
string textt = " USE [DB_SACC] SELECT AVG (Total_Divida) FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
if (textt == null)
{
MessageBox.Show("nothing");
}
else
{
TextBox3.Text = textt;
}
use ExecuteScalar if you request a single value from your database - ExecuteNonQuery returns just the number of affected rows which is used in update / insert statements
USE [DB_SACC] is not required in your query since you define the "Initial Catalog=DB_SACC;"
add using to avoid open connections
Code:
string connectionString = "Data Source=localhost;Initial Catalog=DB_SACC;User id=sa;Password=1234;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
string textt = "SELECT AVG (Total_Divida) FROM t_pagamentos";
using (SqlCommand cmd = new SqlCommand(textt, connection))
{
connection.Open();
var result = cmd.ExecuteScalar(); //write the result into a variable
if (result == null)
{
MessageBox.Show("nothing");
}
else
{
TextBox3.Text = result.ToString();
}
}
}
Use cmd.ExecuteScalar() method instead:
decimal average = (decimal) cmd.ExecuteScalar();
cmd.ExecuteNonQuery(); only returns the number of rows effected where as what you want is to read the result set of SELECT statement.
I would also get rid of USE [DB_SACC] from your SELECT statement since you are defining the database name in your connection string.
EDIT
Your code should look like this:
string textt = "SELECT AVG (Total_Divida) FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
decimal average = (decimal) cmd.ExecuteScalar();
if (textt == null)
{
MessageBox.Show("nothing");
}
else
{
TextBox3.Text = average.ToString();
}
EDIT 2:
try
{
string textt = "SELECT AVG (Total_Divida) FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
decimal average = (decimal)cmd.ExecuteScalar();
TextBox3.Text = average.ToString();
}
catch(Exception ex)
{
// log your exception here...
MessageBox.Show("nothing");
}
EDIT 3:
In the light of your recent comments try this
string connectionString = "Data Source=localhost; Initial Catalog=DB_SACC; User id=sa Password=1234;";
decimal? average;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string textt = "SELECT AVG (Total_Divida) AS 'AVG_DIVIDA' FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
using (DataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
average = decimal.parse(reader["AVG_DIVIDA"].ToString());
break;
}
}
}
}
TextBox3.Text = average.HasValue ? average.ToString() : "Unknown error occurred";
}
catch (Exception ex)
{
MessageBox.Show("Unable to retrieve the average, reason: " + ex.Message);
}
Note: Using DataReader to get just single value from database is not preferred. I am proposing this because of the error you mentioned in the comments.
If you are getting any SQL Exception then try to run this statement on SQL Server as stand alone test.
USE DB_SACC
GO
SELECT AVG (Total_Divida) AS 'AVG_DIVIDA' FROM t_pagamentos
GO
If you still encounter any error while executing T-SQL Statement then please post that as another question.
I am trying to change password option with ms access database....
please help me folks....
here the code:
default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
try
{
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString);
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
OleDbDataReader reader = new OleDbDataReader();
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
reader = cmd.ExecuteReader();
reader.Read();
if (reader["user_id"].ToString() != String.Empty && reader["passwd"].ToString() != String.Empty)
{
if (newPass.Trim() != conPass.Trim())
{
lblmsg.Text = "New Password and old password does not match";
}
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#newPasss", txtnewpass.Text);
cmd.Parameters.AddWithValue("#userod", txtuserid.Text);
cmd.Parameters.AddWithValue("#passwd", txtoldpass.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
lblmsg.Text = "Password changed successfully";
}
else
{
lblmsg.Text = "password not changed";
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
also check pls.....
Compilation Error Description: An error occurred during the
compilation of a resource required to service this request. Please
review the following specific error details and modify your source
code appropriately.
Compiler Error Message: CS0143: The type
'System.Data.OleDb.OleDbDataReader' has no constructors defined
Source Error:
Line 36: OleDbCommand cmd = new OleDbCommand(q, myCon);
Line 37:
Line 38: OleDbDataReader reader = new OleDbDataReader();
Line 39:
Line 40:
As error message says; OleDbDataReader has no constructor.
From documentation of OleDbDataReader;
To create an OleDbDataReader, you must call the ExecuteReader method
of the OleDbCommand object, instead of directly using a constructor.
You can use ExecuteReader method that returns OleDbDataReader
OleDbDataReader dr = cmd.ExecuteReader();
And you need add your parameter values before you call ExecuteReader method.
Also use using statement to dispose your OleDbConnection, OleDbCommand and OleDbDataReader like;
using(OleDbConnection myCon = new OleDbConnection(conString))
using(OleDbCommand cmd = myCon.CreateCommand())
{
//Define your sql query and add your parameter values.
using(OleDbDataReader dr = cmd.ExecuteReader())
{
//
}
}
And as Steve mentioned, OleDbDataReader.Read method returns boolean value (true of false) and it reads your OleDbDataReader results row by row. You might need to consider to use the result of this method like in a while statement. For example;
while(reader.Read())
{
//Reads your results until the last row..
}
As a final words, I strongly suspect you store your passwords as plain text. Don't do that! Use SHA-512 hash.
As MSDN clearly states, To create an OleDbDataReader, you must call the ExecuteReader method of the OleDbCommand object, instead of directly using a constructor.
You cannot instantiate it using new, which is what you are doing and which is why you get the error. Remove the offending line and change it to this to get rid of the error:
OleDbDataReader reader = cmd.ExecuteReader();
Also, remember to use using blocks to ensure resources get properly disposed.
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString))
{
OleDbCommand cmd = new OleDbCommand(q, myCon);
//Add parameters etc
OleDbDataReader reader = cmd.ExecuteReader();
//Rest of the processing
}
Problem: You try to make new instance of OleDbDataReader by calling new OleDbDataReader() instead you should create a reader using OleDbCommand.ExecuteReader().
In the following code notice use of using statement (this should ensure connection closing or reader closing for the case of OleDbDataReader).
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string sConnString = ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString;
using(OleDbConnection myCon = new OleDbConnection(sConnString))
{
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
string sUserId = string.Empty;
string sPass = string.Empty;
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read()) //assumption: one record returned
{
sUserId = reader["user_id"].ToString();
sPass = reader["passwd"].ToString();
}
}
if (sUserId != string.Empty && sPass != string.Empty)
{
if (newPass.Trim() != conPass.Trim())
lblmsg.Text = "New Password and old password does not match";
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#newPass", txtnewpass.Text);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
lblmsg.Text = "Password changed successfully";
else
lblmsg.Text = "password not changed";
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
I get error message :
IErrorInfo.GetDescription failed with E_FAIL(0x80004005)
I think in the code is not any variable that needs [] or?
I was searching and everybody has something to do with [].
string queryString = "SELECT sum(skupaj) FROM cas where sifra = " + textBox1.Text + " and EXTRACT(MONTH FROM Datum) = "+textBox2.Text+"";
try
{
OleDbConnection conn = GetConnection();
OleDbCommand command = new OleDbCommand(queryString, conn);
conn.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
ure = reader.GetValue(0).ToString(); ;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if you just want a sum of something, you dont need a datareader. simply do this:
try
{
OleDbConnection conn = GetConnection();
OleDbCommand command = new OleDbCommand(queryString, conn);
conn.Open();
int count = (Int32) command.ExecuteScalar();
conn.Close();
}
Try to put the table name inside a square bracket like [CAS]. This kind of problem happens if you are using a reserved word in ODBC sql or you are using a field that has space in between then you have to put the field inside a pair of ticks like 'field name'.
I am having trouble with a simple DELETE statement in SQL with unexpected results , it seems to add the word to the list??. Must be something silly!. but i cannot see it , tried it a few different ways. All the same result so quite confused.
public void IncludeWord(string word)
{
// Add selected word to exclude list
SqlConnection conn = new SqlConnection();
String ConnectionString = "Data Source = dev\\SQLEXPRESS ;" + "Initial Catalog=sml;" + "User id=** ;" + "Password =*;" + "Trusted_Connection=No";
using (SqlConnection sc = new SqlConnection(ConnectionString))
{
try
{
sc.Open();
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'" +
conn);
Command.Parameters.AddWithValue("#word", word);
Command.ExecuteNonQuery();
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
finally
{
sc.Close();
}
ExcludeTxtbox.Text = "";
Box.Text = " Word : " + word + " has been removed from the Exclude List";
ExcludeLstBox.AppendDataBoundItems = false;
ExcludeLstBox.DataBind();
}
Try removing the single quotes. Also why are you concatenating your SQL string with a connection object (.. word='#word'" + conn)???
Try like this:
try
{
using (var sc = new SqlConnection(ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM excludes WHERE word = #word";
cmd.Parameters.AddWithValue("#word", word);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
...
Notice also that because the connection is wrapped in a using block you don't need to Close it in a finally statement. The Dispose method will automatically call the .Close method which will return the connection to the ADO.NET connection pool so that it can be reused.
Another remark is that this IncludeWord method does far to many things. It sends SQL queries to delete records, it updates some textboxes on the GUI and it binds some lists => methods like this should be split in separate so that each method has its own specific responsibility. Otherwise this code is simply a nightmare in terms of maintenance. I would very strongly recommend you to write methods that do only a single specific task, otherwise the code quickly becomes a complete mess.
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'" +
conn);
should be replaced with
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'",
conn);
Also try by removing single quotes as suggested by others like this
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word=#word",
conn);
The #Word should not be in quotes in the sql query.
Not sure why you're trying to add the connection on the end of the sql query either.
To debug this, examine the CommandText on the SqlCommand object. Before reading further, you should try this.
The issue comes with adding the single quotes around a string that is parameterized. Remove the single quotes and life is beautiful. :-)
Oh, and your conn is an object and needs a comma, not a +.
See the code below:
private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("delete successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM supplier";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
See the code below:
String queryForUpdateCustomer = "UPDATE customer SET cbalance=#txtcustomerblnc WHERE cname='" + searchLookUpEdit1.Text + "'";
try
{
using (SqlCommand command = new SqlCommand(queryForUpdateCustomer, con))
{
command.Parameters.AddWithValue("#txtcustomerblnc", txtcustomerblnc.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record Update of Customer...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
You can also try the following if you don't have access to some of the functionality prescribed above (due, I believe, to older versions of software):
using (var connection = _sqlDbContext.CreatSqlConnection())
{
using (var sqlCommand = _sqlDbContext.CreateSqlCommand())
{
sqlCommand.Connection = connection;
sqlCommand.CommandText = $"DELETE FROM excludes WHERE word = #word";
sqlCommand.Parameters.Add(
_sqlDbContext.CreateParameterWithValue(sqlCommand, "#word", word));
connection.Open();
sqlCommand.ExecuteNonQuery();
}
}
...
I'm an associate dev. Hence the "I believe" above.
If I run a store procedure with two parameter values (admin, admin)
(parameters : admin, admin)
I get the following message :
Session_UID User_Group_Name Sys_User_Name
------------------------------------ -------------------------------------------------- -
NULLAdministratorsNTMSAdmin
No rows affected.
(1 row(s) returned)
#RETURN_VALUE = 0
Finished running [dbo].[p_SYS_Login].
To get the same message in c# I used the code following :
string strConnection = Settings.Default.ConnectionString;
using (SqlConnection conn = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand())
{
SqlDataReader rdr = null;
cmd.Connection = conn;
cmd.CommandText = "p_SYS_Login";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramReturnValue = new SqlParameter();
paramReturnValue.ParameterName = "#RETURN_VALUE";
paramReturnValue.SqlDbType = SqlDbType.Int;
paramReturnValue.SourceColumn = null;
paramReturnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(paramReturnValue);
cmd.Parameters.Add(paramGroupName);
cmd.Parameters.Add(paramUserName);
cmd.Parameters.AddWithValue("#Sys_Login", "admin");
cmd.Parameters.AddWithValue("#Sys_Password", "admin");
try
{
conn.Open();
rdr = cmd.ExecuteReader();
string test = (string)cmd.Parameters["#RETURN_VALUE"].Value;
while (rdr.Read())
{
Console.WriteLine("test : " + rdr[0]);
}
}
catch (Exception ex)
{
string message = ex.Message;
string caption = "MAVIS Exception";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(
message,
caption,
buttons,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
}
but I get nothing in SqlDataReader rdr ;
is there something I am missing ?
The value at column 0 Session_UID is null as you have shown so I think this may be the reason you are not getting anything here:
Console.WriteLine("test : " + rdr[0]);
but then as an aside you might get Null reference exception.
Still why don't you try this:
Console.WriteLine("Return Value: " + test);
while(rdr.Read()){
Console.WriteLine("test: " + rdr[0]+" " + rdr[1]+ " " + rdr[1]);
}
If you want to get back a return value, but no result rows, you shouldn't be using the .ExecuteReader() but rather the .ExecuteNonQuery() call:
try
{
conn.Open();
object result = cmd.ExecuteNonQuery();
string test = (string)cmd.Parameters["#RETURN_VALUE"].Value;
conn.Close();
}
catch (Exception ex)
{
....
}
Also, since you have your SqlCommand in a using.... block, there's really no point in the finally block of your try - the using statement will take care of that already.