C# update statement with extract - c#

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'.

Related

Display into textbox using if sentence

I'm displaying some data from the database into textboxes on my windows form and I have to add something else but it depends on the account type (that information is saved on my Databse). Meaning it is either DM (domestic) or CM(comercial). I want for it to charge an extra amount if it's CM.
I would appreciate any help, thank you.
OracleDataReader myReader = null;
OracleCommand myCommand = new OracleCommand("SELECT SUM(IMPORTE) AS corriente FROM MOVIMIENTOS WHERE CUENTA='"+txtIngreseCuenta3.Text + "'AND CONCEPTO=10", connectionString);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtCorriente.Text = (myReader["corriente"].ToString());
}
I'm using this code to display into the textbox but I want it to get the account type from another table and IF it's CM then add a certain amount into a textbox.
In your case I suggest that you use Execute Scalar instead of reader since you are returning only one value from the database. but in your case if you want this code to work you need to Cast the returned value into the correct dot net type and then populate the TextBox.
Example Using ExecuteReader
//txtCorriente.Text = ((int)myReader["corriente"]).ToString();
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtCorriente.Text = ((int)reader["corriente"]).ToString();
txtAnother.Text = ((decimal)reader["another"]).ToString();
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Example Using ExecuteScalar
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}

AVG QUERY in c#

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.

SqlDataReader no rows found

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

Retrieve number of columns in SQL Table - C#

I'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:
cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection
You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.
SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')
Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.
You have to use a command and retrieve back the scalar variable :
SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
use Executescalar() for getting a single element.
using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
{
con.Open();
try
{
using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
{
Int32 count = (Int32)getchild.ExecuteScalar();
}
}
}
Use ExecuteScalar
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
colnumber = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.
using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
SqlCommand cmd=new SqlCommand(Query,conn);
try
{
conn.Open();
}
catch (SqlException se)
{
throw new InvalidOperationException(String.Format(
"Connection error: {0} Num:{1} State:{2}",
se.Message,se.Number, se.State));
}
resultVar = (string)cmd.ExecuteScalar().ToString();
conn.Close();

SQL delete command?

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.

Categories

Resources