Print My Search Results From SQL Server on label - c#

I'm just trying to print the sum of my search on a label in form.
Story is I have 2 textboxes that will give me 2 date and searching in my database, and printing the answer of sum cost between that 2 date.
My code is :
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True");
SqlCommand com = new SqlCommand();
if (con.State == ConnectionState.Closed)
{
con.Open();
com = new SqlCommand("select sum (Cost) as JameKol From TBL_Cost Where CostDate between '" + textBox1.Text + "' and '" + textBox2.Text + "' ", con);
label5.Text = com();
con.Close();
MessageBox.Show("Search is done", "Done");
}
}
com can't use as a method, so, how can I do this?

Just use ExecuteScalar which is exactly what this for. It gets first column of the first row which fits SUM function.
label5.Text = com.ExecuteScalar().ToString();
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connection and command automatically instead of calling Close method manually.
By the way, looks like your CostDate column is character typed. Don't do it. This is a bad habit to kick. You should never keep your DateTime values as a character. Change it to datetime or better datetime2 type and pass your DateTime values directly to your parameterized query. That's why I used DateTime.Parse to parse your Text values. If it can't parse them, you can use ParseExact as well.
string conString = "Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True";
using(var con = new SqlConnection(conString))
using(var com = con.CreateCommand())
{
com.CommandText = #"select sum (Cost) as JameKol From TBL_Cost
Where CostDate between #date1 and #date2";
com.Parameters.Add("#date1", SqlDbType.DateTime2).Value = DateTime.Parse(textBox1.Text);
com.Parameters.Add("#date2", SqlDbType.DateTime2).Value = DateTime.Parse(textBox2.Text);
con.Open();
label5.Text = com.ExecuteScalar().ToString();
}

Related

When trying to retrieve data from the database I get an error "InvalidOperationException was unhandled"

I have a form named Form1:
There is one ComboBox and one TextBox, when I select US$ from the ComboBox then it must retrieve data from the database and display 150 in the TextBox.
This is myform code:
For ComboBox;
namespace PCJ_System
{
public partial class Form1 : Form
{
SqlConnection conn;
SqlCommand cmd;
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";
SqlConnection conn = new SqlConnection(str);
conn.Open();
conn = new SqlConnection(str);
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}
}
My database table Forcur:
ID |FC_TYPE |FC_RATE|
1 US$ 150
2 UK# 210
What's wrong with my code?
This might not be the exact answer you are looking for, but you need to take care of following:
1) Assign DB connection string to SqlConnection object and open connection.
2) Since you are assigning one value to textbox, you need to use ExecuteScalar instead of ExecuteReader
Once you fix this, you should get the desired result.
Example:
conn=new SqlConnection(connectionStringHere);
conn.Open();
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.close();
Note: You still have SQL injection attack open in your SQL query. Try using varables instead to stop that.

UPDATE statement is not updating results in SQL Server

I am trying to update result in SQL server with below query but its not updating. If i write (update lunTime set lunOut = '2014-12-08 23:23:23.120' where empName='Mike' and
date='2014-12-08') it is updating it.
protected void btnLunOut_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection(
"Data Source=myServer;Initial Catalog=MY_Srv;Integrated Security=True");
conn1.Open();
SqlCommand cmd = new SqlCommand(
"Update [lunTime] SET lunOut = #LunOUT where (empName=#EmpName and date=#Date)",
conn1);
cmd.Parameters.AddWithValue("#EmpName", drpDwnEmp.Text);
cmd.Parameters.AddWithValue("#LunOUT", DateTime.Now);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.ExecuteNonQuery();
conn1.Close();
drpDwnEmp.Text = string.Empty;
}
Most likely it simple does not find the record for data == DateTime.Now case.
It is unlclear what you want to achieve, but maybe some range conditions on date variable or Now.Date is the solution (assuming date is actually date only, no time portion):
cmd.Parameters.AddWithValue("#Date", DateTime.Now.Date);

How to convert C# DateTime to MySQL timestamp table column

I'm trying to update a table element of type timestamp called dtprint with the current time (the original value is NULL). The code that I am using is as follows:
MySqlConnection con = new MySqlConnection("Connection_String");
con.Open();
MySqlCommand _cmd = con.CreateCommand();
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
_cmd.CommandText = "UPDATE requests SET dtprint = " + dt + " WHERE idPerson = " + _personID[index];
_cmd.ExecuteNonQuery();
con.Close();
The exception I keep getting is: Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '14:03:23 WHERE idPerson = 45' at line 1.
The only thing I can think of is that the Database isn't recognizing the time as a timestamp, any help is greatly appreciated.
Since dt is a string and your dtprint is timestamp, you need to use single quotes when you try to insert it. Like;
"UPDATE requests SET dtprint = '" + dt + "' WHERE
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your database connections and objects.
using(MySqlConnection con = new MySqlConnection(ConnectionString))
using(MySqlCommand _cmd = con.CreateCommand())
{
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
_cmd.CommandText = #"UPDATE requests SET dtprint = #dtprint
WHERE idPerson = #id";
_cmd.Parameters.Add("#dtprint", MySqlType.TimeStamp).Value = dt;
_cmd.Parameters.Add("#id", MySqlType.Int).Value = _personID[index];
con.Open();
_cmd.ExecuteNonQuery();
}

Syntax error in UPDATE statement in C# asp.net

So, I'm quite new to C#. I have a a gridview row on my page. Once I edit the data, I want it updated also in the access database that is linked to it. I get this error: Syntax error in UPDATE statement. I think my date is the one to blame but still... I can't find out what I'm doing wrong.
Here's the code for my update row function:
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string id = (row.Cells[0].Controls[0] as TextBox).Text;
string nume = (row.Cells[1].Controls[0] as TextBox).Text;
string prenume = (row.Cells[2].Controls[0] as TextBox).Text;
string data = (row.Cells[3].Controls[0] as TextBox).Text;
DataTable dt = ViewState["dt"] as DataTable;
//dt.Rows[row.RowIndex]["ID"] = id;
dt.Rows[row.RowIndex]["Nume"] = nume;
dt.Rows[row.RowIndex]["Prenume"] = prenume;
dt.Rows[row.RowIndex]["Data Nasterii"] = data;
ViewState["dt"] = dt;
GridView1.EditIndex = -1;
OleDbConnection con; // create connection
OleDbCommand com; // create command
con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db\db1.mdb");
con.Open();
DateTime date = Convert.ToDateTime(data);
com = new OleDbCommand("Update Table1 set Nume=" + nume + " , Prenume=" + prenume + ", Data Nasterii= #date where ID=" + id, con);
com.Parameters.AddWithValue("#date", OleDbType.Date).Value=data;
com.ExecuteNonQuery();
con.Close();
this.BindGrid();
Response.Write("alert('DATA UPDATED')");
}
Can anyone help me?
If your column name has two words, you need to use square brackets with it. Like;
[Data Nasterii] = #date
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
I see you parameterized your data value, parameterize your other values as well.
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
// Set your CommandText property.
// Define and add your parameter values.
// Open your OleDbConnection.
// Execute your query.
}

What is the optimal / standard method of using a sql connection?

protected void populateDataGrid()
{
string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string command = "select * from student";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString);
DataSet data = new DataSet();
dataAdapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (studentID, studentFirstName, studentLastName)
VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
The first function gets all the table data and dumps it to a gridview.
The second function takes input and inserts it into the database.
How can these functions be condensed or simplified?
How can these functions be condensed or simplified?
I would focus on correctness before simplification. Currently I can see at least two problems with the code:
You should absolutely use parameterized SQL instead of putting the values into the SQL itself. Your current code is prone to SQL injection attacks.
You should use using statements so that connection and command are both closed automatically even if exceptions are thrown.
Then in terms of simplification:
You can use the SqlCommand constructor which takes the text and connection - the type defaults to Text anyway.
I would personally try to separate the UI code from the storage code, at least for a non-trivial project. You should look at ASP.NET MVC, at least to get some idea of separation, even if you don't change to start using it.
In Button2_Click(object sender, EventArgs e) method , you need to use parametrized query to avoid SQL Injection.
That is the standard way.
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (
studentID, studentFirstName, studentLastName
) VALUES (
#studID, #FName, #LName
)";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Parameters.AddWithValue("#studID", TextID.Text);
cmd.Parameters.AddWithValue("#FName", TextFirstName.Text);
cmd.Parameters.AddWithValue("#LName", TextLastName.Text);
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
Hope Its Helpful.

Categories

Resources