In SQL Server Management studio, when you do a SELECT query, you also get a message aswell as the results. That message i would like to use in a Rich Textbox. Is that possible?
The Message i'm talking about is this:
I have this code so far, that also fills comboboxes with results, but i would like my rich textbox to show the message aswell:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
Con.Close();
}
The GUI looks like this:
Use SqlConnection.InfoMessage event,
This event occurs when SQL Servers returns a warning or informational message.
You don't need to look at the message. You can just look at the reader's RowsEffected, like this :
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
var recordsEffected = reader.RecordsAffected;
}
ExecuteNonQuery() - returns the number of rows affected.
SqlCommand comm;
// random code
int numberOfRecords = comm.ExecuteNonQuery();
EDIT:
For select queries you can use ExecuteScalar() -
String sqlQuery = "SELECT count(USERNAME) FROM PERSONAL";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
try
{
conn.Open();
//Since return type is System.Object, a typecast is must
count = (Int32)cmd.ExecuteScalar();
}
I got it all to work. Thanks for the big help. Much apprieciated!
I will show it all if any can use any off it :D
Ended up with this:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
}
var countUsers = fromComboBox.Items.Count;
movePostMessage.Text = countUsers + " brugere er fundet";
}
}
And on the button click i've made this:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
string SQL1 = "UPDATE DEBSALDO SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL2 = "UPDATE SERVHEAD SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL3 = "UPDATE SERVICEB SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL4 = "UPDATE PERSONAL SET ACOUNTCYID = NULL WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
SqlCommand cmd1 = new SqlCommand(SQL1, Con);
SqlCommand cmd2 = new SqlCommand(SQL2, Con);
SqlCommand cmd3 = new SqlCommand(SQL3, Con);
SqlCommand cmd4 = new SqlCommand(SQL4, Con);
Int32 rowsAffectedOnUpdate1 = cmd1.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate2 = cmd2.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate3 = cmd3.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate4 = cmd4.ExecuteNonQuery();
movePostMessage.Text = rowsAffectedOnUpdate1 + " regninger flyttet fra tidligere brugers debitor saldo \r\n" + rowsAffectedOnUpdate2 + " regninger flyttet med tidligere bruger som ejer \r\n" + rowsAffectedOnUpdate3 + " ydelser flyttet med tidligere bruger som ejer \r\n" + rowsAffectedOnUpdate4 + " kontoplan nulstillet";
}
And the GUI to it:
Related
The problem says:
Too few parameters. Expected 1.
Here's my database table:
CustomerOrder [CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate]
Code:
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate)values('" + txtOrderCode.Text + "','" + txtProdName.Text + "', '" + txtProdPrice.Text + "', '" + txtOrderQty.Text + "', '" + txtCatName.Text + "', '" + txtOrderDate.Text + "')";
cmd.ExecuteNonQuery();
tabControl1.SelectedTab = tabPage1;
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
int ordercode, orderqty;
double price;
string prodname, catname;
ordercode = Convert.ToInt32(txtOrderCode.Text);
orderqty = Convert.ToInt32(txtOrderQty.Text);
price = Convert.ToDouble(txtProdPrice.Text);
prodname = Convert.ToString(txtProdName.Text);
I would recommend you use parametrised queries instead as it will prevent you from Sql Injection Attacks. Here is a small example of how it could work with your code
String SqlCommand = "insert into CUSTOMERORDER values (#OrderId, #ProdName,#ProdPrice,#OrderQty, #CatName,#OrderDate)";
SqlCommand cmd = new SqlCommand(SqlCommand , //ConnectionString);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#OrderId", txtOrderCode.Text);
cmd.Parameters.AddWithValue("#ProdName", txtProdName.Text );
cmd.Parameters.AddWithValue("#ProdPrice", txtProdPrice.Text);
cmd.Parameters.AddWithValue("#OrderQty", txtOrderQty.Text);
cmd.Parameters.AddWithValue("#CatName", txtCatName.Text.Text);
cmd.Parameters.AddWithValue("#OrderDate", txtOrderDate.Text);
cmd.ExecuteNonQuery();
conn.Close();
Read up on Sql Injection attacks. Doing it this way is much easier, cleaner and most importantly, safer. Also when looking at your code you are setting the text box values after you have ran the Sql command
I have two buttons, SetIn and SetOut. They both have the commandName UPDATE ( I have two buttons as I'd like the text to be different on the button depending on the value of one field in the row.
I'm getting a problem in that when I run the update SQL statement, it throws an error at me. It says:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '14'.
This means that there is an issue with the date and time stamp that I am trying to update the row with (I'm making the update at 14.02pm).
My aspx.cs page code is:
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_Index") as Label;
int rowToUpdate = Int32.Parse(id.Text);
con = new SqlConnection(cs);
int scopeValue;
con = new SqlConnection(cs);
cmd = new SqlCommand();
cmd.CommandText = "SELECT in_scope FROM " + databaseName + " WHERE id = '" + rowToUpdate + "'";
cmd.Parameters.AddWithValue("#id", rowToUpdate);
cmd.Connection = con;
try
{
con.Open();
scopeValue = Convert.ToInt32(cmd.ExecuteScalar());
//database_entries.Text = recordCount.ToString();
}
finally
{
con.Close();
}
string modifiedBy = userManagement.getWeldID();
string updateDate = DateTime.UtcNow.ToString("dd/MMM/yyyy HH:mm:ss");
{
if (scopeValue == 1)
{
// Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_Index") as Label;
string sqlStatement = "";
con = new SqlConnection(cs);
// SqlCommand cmd = new SqlCommand();
sqlStatement = #"update dbo.Fair_Use_InScope_MIF_Alex_temp set in_scope = '0', modified_by = " + modifiedBy + ", date_updated = " + updateDate + " where id = '" + rowToUpdate + "'";
con.Open();
cmd = new SqlCommand(sqlStatement, con);
cmd.ExecuteNonQuery();
con.Close();
ShowData();
}
if (scopeValue == 0)
{
// Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_Index") as Label;
string sqlStatement = "";
con = new SqlConnection(cs);
// SqlCommand cmd = new SqlCommand();
sqlStatement = #"update dbo.Fair_Use_InScope_MIF_Alex_temp set in_scope = '1', modified_by = " + modifiedBy + ", date_updated = " + updateDate + " where id = '" + rowToUpdate + "'";
con.Open();
cmd = new SqlCommand(sqlStatement, con);
cmd.ExecuteNonQuery();
con.Close();
ShowData();
}
}
}
I'm basically trying to get the scopeValue (0 or 1) of the row, and if the Update command is called, and the scopeValue was previously 0, set it to 1 now and vice versa. I also need to update the time that the change was made and who made the change in that row. (these are both displayed in the gridview)
Any help would be much appreciated as I am a beginner to ASP.NET and C# and SQL SERVER!!
You are sending a DateTime as a string (without even enclosing single quotes date_updated = '" + updateDate + "') and that will always cause problems.
It's better to use parameters in your query. This prevents SQL injection, improves readability, ensures type safety, no more worries about the correct use of quotation marks etc.
string sqlStatement = "UPDATE dbo.Fair_Use_InScope_MIF_Alex_temp SET in_scope = 0, modified_by = #modifiedBy, date_updated = #updateDate WHERE (id = #rowToUpdate)";
using (SqlConnection connection = new SqlConnection(cs))
using (SqlCommand command = new SqlCommand(sqlStatement, connection))
{
command.Parameters.Add("#modifiedBy", SqlDbType.VarChar).Value = modifiedBy;
command.Parameters.Add("#updateDate", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#rowToUpdate", SqlDbType.Int).Value = 35;
connection.Open();
command.ExecuteNonQuery();
}
The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End
Let me first explain my code.
fetch fare for selected destination(reader1)
fetch * for selected user id(reader2)
insert data to process new balance(cmd3)
retrieve new balance as calculated field (reader3)
update travel account (cmd5)
clear calc_tb for next customer input(cmd6)
My problem is while running, I get this error:
There is already an open DataReader associated with this Command which must be closed first.
How can I handle more than one DataReader accessing different tables?
Is DataReader similar to resultset in Java ?
I'm a beginner in coding.
string id,
destin, num;
id = txt_id.Text;
destin = cb_destin.Text;
num = cb_num.Text;
string sql1 = "SELECT fare FROM route_info WHERE route_name='" +destin + "' ";
string sql2 = "SELECT * FROM trav_acc WHERE user_id='" + id + "'";
con.Open();
cmd1 = new SqlCommand(sql1, con);
reader1 = cmd1.ExecuteReader();
while(reader1.Read())
{
string fare = (string)reader1["fare"];
cmd2 = new SqlCommand(sql2, con);
reader2 = cmd2.ExecuteReader();
string cur_bal = (string)reader2["cur_bal"];
reader2.Close();
string calc1 = "INSERT INTO calc_tb VALUES('" + cur_bal + "','" + num + "','" + fare + "')";
string calc2 = "SELECT cur_bal - (nof_tickets * fare) AS new_bal FROM calc_tb";
cmd3 = new SqlCommand(calc1, con);
cmd3.ExecuteNonQuery();
cmd4 = new SqlCommand(calc2, con);
reader3 = cmd4.ExecuteReader();
while(reader3.Read())
{
string new_bal = (string)reader3["new_bal"];
string update = "UPDATE trav_acc SET cur_bal='" + new_bal + "',last_bal='" + cur_bal + "' WHERE user_id='" + id + "' ";
cmd5 = new SqlCommand(update, con);
cmd5.ExecuteNonQuery();
string clear = "DELETE FROM calc_tb";
cmd6 = new SqlCommand(clear, con);
cmd6.ExecuteNonQuery();
}
}
con.Close();
MessageBox.Show("Thank you for using EasyTravel.Come again soon!");
}
It seems that reader3 and cmd4 are defined outside of the code you are showing us, but at least they are defined outside the loop for reader1. So if your reader1 contains more than one row, reader3 and cmd4 will be assigned again, but the "old" reader3 is never closed. Close reader3 when it's finished reading. Or use a using statement, which will take care of the closing automatically.
using (DataReader reader1 = cmd1.ExecuteReader()) {
....
while (reader1.Read()) {
....
using (DataReader reader3 = cmd4.ExecuteReader()) {
while (reader3.Read()) {
}
} //reader3 is closed here automatically
}
} //reader1 is closed here automatically
Furthermore, I'm not sure if I remember correctly, but I think it's not possible to have two open readers on the same connection. I may be wrong with this, though.
String sqlCheckPass =
"Select * from Login where Username like #Username and Password like #Password";
SqlCommand SqlCom = new SqlCommand(sqlCheckPass, myConnection);
SqlCom.Parameters.Add(new SqlParameter("#Username", sUserName));
SqlCom.Parameters.Add(new SqlParameter("#Password", sPassword));
myConnection.Open();
SqlDataReader myreader;
myreader = SqlCom.ExecuteReader();
int id = -1;
ErrorBox.InnerHtml = "Username:" + sUserName + ":" + sPassword + ":<br/>";
while (myreader.HasRows)
{
id = (int)myreader["id"];
String sUser = (String)myreader["Username"];
String sPass = (String)myreader["Password"];
ErrorBox.InnerHtml += "UserId is <b>" + id + "</b> " + sUser + ":" + sPass + ":<br >";
Session["LoginID"] = id;
Server.Transfer(ReturnPage);
}
if (id == -1)
{
ErrorBox.InnerHtml = "Incorrect Password";
}
myConnection.Close();
catch (Exception err)
{
ErrorBox.InnerHtml = "Error Getting Option ID" + err.Message;
}
I added a breakpoint at myreader = SqlCom.ExecuteReader(); and it keeps returning myreader as null and HasRows = False, but it does have rows. So, it keeps validating my login as incorrect since id = -1,
Help?
You didn't connect your reader to your SQL connection/command?
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
The problem might be the LIKE in your query with the SqlParameters. Try
String sqlCheckPass =
"Select * from Login where Username like '%' + #Username + '%' and Password like '%' + #Password + '%'";
Bryan Denny's answer above is correct, however, I'll enclose all of the code inside using statements as shown below:
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand SqlCom = dataConnection.CreateCommand())
{
SqlCom.CommandText = "Select * from Login where Username like #Username and Password like #Password";
SqlCom.Parameters.Add(new SqlParameter("#Username", sUserName));
SqlCom.Parameters.Add(new SqlParameter("#Password", sPassword));
dataConnection.Open();
SqlDataReader myreader;
myreader = SqlCom.ExecuteReader();
dataConnection.Close();
}
}
I didn't add all of your code to this snippet, I figured you get the idea.
Also, you could try modifying the select statement to return a count of records since this is all you need anyways, a number:
SELECT COUNT(*) FROM Login WHERE Username like #Username AND Password like #Password
Good luck!