I have cookies named empid which stores the id of employee i am going to use. But whenever i try to get the value of any cookie its value is set to null automatically and this code is from a partial class which is inherited by page . What if i want to create a class that contains all the database related code and want to use it in everypage
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
cn.Open();
SqlDataReader conReader;
conReader = null;
mycomment.Text = Response.Cookies["empid"].Value;
// cmd.CommandText = "Select * from comments where c_from = " + Response.Cookies["cid"] + " and c_to = "+ Response.Cookies["empid"].ToString();
cmd.Connection = cn;
mycomment.Text = cmd.CommandText;
cmd.CommandType = CommandType.Text;
conReader = cmd.ExecuteReader();
while (conReader.Read())
{
mycomment.Text += conReader[3].ToString();
}
}
catch (Exception ex)
{
Console.Write(ex);
}
finally
{
cn.Close();
}
}
}
}
You're getting Cookies from the Response object - which is the outgoing cookies set, not the Request object which is the set of cookies coming from the client.
Change it to mycomment.Text = this.Request.Cookies["empid"].Value.
I also see you're forming SQL commands by using String Concatenation without any sanitation. DO NOT EVER DO THIS. Instead use parameters:
cmd.CommandText = "SELECT * FROM comments WHERE c_from = #from AND c_to = #to";
cmd.Parameters.AddWithValue("#from", this.Request.Cookies["cid"].Value);
cmd.Parameters.AddWithValue("#to" , this.Request.Cookies["empid"].Value);
Related
I am creating a basic app for adding and displaying customer information using windows forms in visual studio. i have set it up so i am able to display the contents of the database in a gridview and also add to the database which you can see the code for below. what i am stuck on at the moment is updating the customers information. I want to search the database by customerID which will be entered by the user in a textbox, and display that specific customers details into their relevent textboxes which i can then edit and save.
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"INSERT INTO customer (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance)";
cmd.Parameters.AddWithValue("setTitle", cb_title.Text);
cmd.Parameters.AddWithValue("setFirstname", txtFirst_Name.Text);
cmd.Parameters.AddWithValue("setLastname", txtSurname.Text);
cmd.Parameters.AddWithValue("setDOB", dtp_DOB.Text);
cmd.Parameters.AddWithValue("setNICode", txtNI_Code.Text);
cmd.Parameters.AddWithValue("setEmail", txtEmail.Text);
cmd.Parameters.AddWithValue("setPassword", txtPassword.Text);
cmd.Parameters.AddWithValue("setAllowance", txtAllowance.Text);
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Added");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
That's what I have for adding a new customer which works fine
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"UPDATE customer SET (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance) WHERE custid = #recd";
cmd.Parameters.AddWithValue("title", cb_title_update.Text);
cmd.Parameters.AddWithValue("firstname", txtFirst_Name_update.Text);
cmd.Parameters.AddWithValue("lastname", txtSurname_update.Text);
cmd.Parameters.AddWithValue("dob", dtp_DOB_update.Text);
cmd.Parameters.AddWithValue("nicode", txtNI_Code_update.Text);
cmd.Parameters.AddWithValue("email", txtEmail_update.Text);
cmd.Parameters.AddWithValue("password", txtPassword_update.Text);
cmd.Parameters.AddWithValue("allowance", txtAllowance_update.Text);
cmd.Parameters.AddWithValue("recd", Convert.ToInt32(txtSearch.Text));
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Updated");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
And that's the code I have so far for updating the database, but I can not figure out how to retrieve the customer data and display it into the textboxes, any help or guidance would be appreciated
Your Update statement is not correct. Try the following.
cmd.CommandText =#"UPDATE customer
SET title = #setTitle,
firstname = #setFirstname,
lastname = #setLastname
dob = #setDOB,
nicode = #setNICode,
email = #setEmail,
password = #setPassword,
allowance = #setAllowance
WHERE custid = #recd";
It is a bit different from an Insert. Each field is set to a new value. You don't need all that concatenation. This is a literal string.
Of course, in a real application you would NEVER store passwords as plain text.
To get the value of a certain column from a certain row, you can try to call method SqlCommand.ExecuteReader.
Here assume you want to get the the customer password.
string connectionstring = #"connectin string";
private void btnSearch_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from customer where customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
conn.Open();
try
{
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (reader.HasRows)
{
if (reader.Read())
{
// get password column value
textBoxPWD.Text = reader["password"].ToString();
}
}
else
{
Console.WriteLine("no such record");
}
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}
As to update the record,
private void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE customer SET password = #cusPWD WHERE customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
cmd.Parameters.AddWithValue("#cusPWD", textBoxPWD.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
I want to pass the information I get from a database to a label. How can I pass the information into a variable.
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
var numero = textBox1.Text;
string connection_string = "datasource=xxx;port=111;username=xxx;password=xxx";
string Query = "select * from xxx.lojass where nome =" + numero;
MySqlConnection conDate = new MySqlConnection(connection_string);
MySqlCommand cmdDate = new MySqlCommand(Query, conDate);
MySqlDataReader myReader;
try
{
conDate.Open();
myReader = cmdDate.ExecuteReader();
MessageBox.Show("Conected");
while (myReader.Read())
{
label1.Text
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Proper coding. Explanation in code comments below
private void button1_Click(object sender, EventArgs e)
{
try
{
const connStr = "datasource=xxx;port=111;username=xxx;password=xxx"; // constant
// Instead of "select *" select particular column(s), it will help with reader columns later
var sql = "select column1 from xxx.lojass where nome = #1"; // you need to parameterize. Never push text box value directly into sql
// important to use "using" to release resources
using (var conn = new MySqlConnection(connStr))
{
using (var cmd = new MySqlCommand(sql, conn))
{
// assuming "nome" is string. If the value is other datatype - convert it
// Better yet - create parameter where you explicitly specify mySql data type
cmd.Parameters.AddWithValue("#1", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader()) // Since single value expected another way doing it - ExecuteScalar
{
// you only fill one single value, so makes sense to use IF, not WHILE
if (reader.Read())
label1.Text = reader["column1"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm trying to finish a college project that requires a program to interact with a database.
Some of my naming is a little odd, but don't worry!
I'm trying to use a single submit button to either update or insert to the database.
Main issue is that I can't get an update to work though when I changed my code to try and fix it, I made it worse. Here is what I currently have.
private void btn_submit_Click(object sender, EventArgs e)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT TaskCode FROM TaskCode;";
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
SqlCeDataReader reader;
reader = c1.ExecuteReader();
if (reader.Read())
{
try
{
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, TaskDescription = #TaskDescription = WHERE TaskCode = #TaskCode;";
SqlCeCommand c = new SqlCeCommand(taskUpdate, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been updated");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
else
{
try
{
string taskInsert = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
SqlCeCommand c = new SqlCeCommand(taskInsert, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
}
}
Has anyone got any ideas why I am getting an error on the c.ExecuteQuery line?
If I remove said line, it will not throw an exception, but it will not update the database.
Thanks
You have a simple syntax error in your update query just before the where statement.
There is an invalid equal sign
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
Your query also could be simplified with
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT COUNT(*) FROM TaskCode";
string cmdText;
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
int count = (int)c1.ExecuteScalar();
if (count > 0)
{
// Here there is no point to update the TaskCode. You already know the value
// Unless you have a different value, but then you need another parameter
// the 'old' TaskCode.....
cmdText = "UPDATE TaskCode SET " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
}
else
{
cmdText = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
}
try
{
SqlCeCommand c = new SqlCeCommand(cmdText, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
MessageBox.Show(count > 0 ? "Record has been updated" : "Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
Not sure if it is the only problem, but you have an equal (=) sign before the WHERE keyword.
When I select the in the gridview using checkbox, I want it to insert the data into the database, but it is not adding it. My code is below, please see where I am going wrong.
public partial class HomeTeamCheckList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LiveGameReporting Window
SubmitLineUp.Attributes.Add("onclick", "PassValues();");
SubmitLineUp.Text = "Submit " + Session["HomeTeam"] + "'s Line Up";
}
protected void SubmitLineUp_Click(object sender, EventArgs e)
{
String GameID = string.Empty;
String Name = string.Empty;
String Number = string.Empty;
int GKGVCount = GoalKeeperGridView.Rows.Count;
foreach (GridViewRow gkrow in GoalKeeperGridView.Rows)
{
GameID = (String)Session["GameID"];
Number = gkrow.Cells[0].Text;
Name = gkrow.Cells[1].Text;
SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = #"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (#GameID,#Number,#Name)";
cmd.Parameters.AddWithValue("#GameID", GameID);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
}
}
}
Two thoughts:
Use a try-catch to see if you're getting any SQL errors.
Check the return value of the cmd.ExecuteNonQuery(); to see if any rows were actually affected / inserted.
Like this:
SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = #"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (#GameID,#Number,#Name)";
cmd.Parameters.AddWithValue("#GameID", GameID);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
// use a debugger to see if any rows were actually affected / inserted
int rowsAffected = cmd.ExecuteNonQuery();
}
catch(SQLException error)
{
// Use a debugger to see if you are getting an error on execution
string errorText = error.message;
}
Your query string looks ok, so it could be a permissions error. But the steps above will help you track it down.
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.