Select query does not retrieve info from db after insert into query - c#

I've built an app in vs 2012 that is supposed to be able to select, insert, update, delete info from a sql server 2012 database. At first I put some data into the db using sql server. I built my select queries to test them out and they worked. After this I built my insert query and tested it out. It also works. But if I try to retrieve data that I have inserted, it doesn't retrieve anything.
Here's an example of one of my select queries:
query = "SELECT P.Denumire, P.Pret, P.Cantitate, P.Reducere, P.Pret_redus, " +
"S.Stoc_magazin, S.Stoc_depozit " +
"FROM Produse P, Stoc_intern S " +
"WHERE S.ID_produs IN " +
"(SELECT P.ID_produs " +
"FROM Produse " +
"WHERE P.Denumire LIKE '%" + tb_s_name.Text + "%')";
SqlDataAdapter da = new SqlDataAdapter(query, c);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
q_res.DataSource = dt;
And here's and example of one of my insert queries:
query = "Insert INTO Produse " +
"(Denumire, Pret, Cantitate, Reducere) " +
"Values(#Denumire, #Pret, #Cantitate, #Reducere)";
SqlCommand cmd = c.CreateCommand();
cmd.Connection = c;
cmd.CommandText = query;
cmd.Parameters.Add("#Denumire", SqlDbType.NVarChar, 50).Value = tb_op_name.Text;
cmd.Parameters.Add("#Pret", SqlDbType.Float).Value = tb_op_pv.Text;
cmd.Parameters.Add("#Cantitate", SqlDbType.NVarChar, 50).Value = tb_op_cantitate.Text;
cmd.Parameters.Add("#Reducere", SqlDbType.Float).Value = tb_op_red.Text;
cmd.ExecuteNonQuery();
Both queries work, it's just that if I submit the insert query and after try to select something with the select query, it does not retrieve anything although the information exists in the database. I checked by opening the db in sql server after executing the insert query from my vs built app.
Here's the connection string also:
SqlConnection c = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Application.StartupPath + #"\DB\Supermarket.mdf;Integrated Security=True;MultipleActiveResultSets=true;Connect Timeout=30");

Please use different SqlConnections for each procedure.

Related

Database insert error: "string or binary data would be truncated"

When I log in, I am storing my username in the session. My requirement is that I want to store my username in my database. Here I am storing it in username1. When the username is entered, I can print it using response.write() and it is printing perfectly. However, when I am storing it in the database it is producing this error:
**sqlException was unhandled by user code
and exception at cmd.ExecuteScalar();
String or binary data would be truncated.
The statement has been terminated.**
Following is my ado.net code:
using (SqlConnection con =
new SqlConnection("Data Source=.;database=testdb1;Integrated Security=SSPI")) {
con.Open();
// SqlCommand cmd = new SqlCommand("delete from fileinfo where ID=" + Convert.ToInt32(Request.Params["one"]), con);
string uname = (string) Session["fname"].ToString() + " " + Session["lname"].ToString(); //Session["fname"].ToString()+" "+Session["lname"].ToString();
// Response.Write(uname);
// uname = "sri hari";
uname = uname + " ";
string uname1 = uname;
uname = uname.Trim();
SqlCommand cmd = new SqlCommand("insert into qry_details values('" + txt_query_name.Text + "','pending for approval','" + txt_query_description.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + qry + "','" + uname1 + "')", con);
cmd.ExecuteScalar();
}
check the length of qry_details table and see if its smaller than the string you send to the db?
basically the exception says you are trying to something bigger than the column length.
I would recommend you using a parametrized query. Your code is now vulnerable to SQL injection. Also you should use the ExecuteNonQuery method on the SQL command instead of ExecuteScalar when inserting values to the database:
var connectionString = "Data Source=.;database=testdb1;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "INSERT INTO qry_details VALUES (#query_name, 'pending for approval', #query_description, #date, #qry, #username)";
cmd.Parameters.AddWithValue("#query_name", txt_query_name.Text);
cmd.Parameters.AddWithValue("#query_description", txt_query_description.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#qry", qry);
cmd.Parameters.AddWithValue("#username", uname1);
cmd.ExecuteNonQuery();
}
This error mostly happen when the inserting value is larger than the field width defined in table on SQL Server.
Check if you are inserting date and time using DateTime.Now c# fuction, your Table must be of type DateTime. not Date or Time only.

selecting data between 2 dates

I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'

Parameterize a SELECT ROWCOUNT sql statement

I am using VS2005 C# and SQL Server 2005.
I have a a few SQL queries which I am converting them from using parameters instead concatenations for SQL injection prevention.
Below is a SELECT query which is parameter-ed:
string loggedinuser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [UserTable] where [" + DropDownList1.Text + "] like #searchtb AND [LoggedInUser] LIKE #userlog";
SqlDataSource1.SelectParameters.Add("searchtb", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("userlog", "%" + loggedinuser+ "%");
The above sql query searches for records base on the user's input in a search textbox and return results which matches the search input and username in the database.
I have another SQL query which is also a SELECT statement. However, this time it does not use SqlDataSource, but using cmd instead. Thus I need some help in converting the SQL statement below to parameter form:
string loggedinuser = (User.Identity.Name);
string stmt = "SET ROWCOUNT 1 SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [LoggedInUser] LIKE '%"+loggedinuser +"%'";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
This SQL query searches for number of records that the user is trying to search base on his search input and username. And if countuser returns a 0 value, I will prompt the user after that.
I need help in converting the 2nd SQL statement into parameter form.
Thank you.
Try,
string stmt = "SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "]
like #searchTb AND [LoggedInUser] LIKE #loggedinuser";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
cmdCount.Parameters.Add("#searchTb",SqlDbType.VarChar,40).Value="%" + searchTB.Text + "%";
cmdCount.Parameters.Add("#loggedinuser",SqlDbType.VarChar,40).Value="%" + loggedinuser + "%";
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
Using stored procedures is your best bet, but if you cannot use them, this code should work:
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = #au_id", conn);
SQLParameter parm = myCommand.SelectCommand.Parameters.Add("#au_id",
SqlDbType.VarChar, 11);
Parm.Value = Login.Text;
This is from the MSDN article on SQL injection.
http://msdn.microsoft.com/en-us/library/ms161953.aspx

how to improve this code

// conn is read from handydrive
//conn2 read from C:\
this code is for write new record in to DB in C:\ by check exist first.
my problem is too slow for alot of records. and how to improve it to be faster...
SqlCeCommand cmd1 = new SqlCeCommand("Select * from bill_discount ", conn);
SqlCeDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read() != false)
{
SqlCeCommand cmd4 = new SqlCeCommand("Select * from bill_discount where bill_no='" + dr1.GetInt32(0) + "' AND bill_shopdc='" + dr1.GetString(2) + "' ", conn2);
SqlCeDataReader dr4 = cmd4.ExecuteReader();
if (dr4.Read() == false)
{
SqlCeCommand cmd2 = new SqlCeCommand("INSERT INTO bill_discount (bill_no,bill_value,bill_shopdc) VALUES ('" + dr1.GetInt32(0) + "','" + dr1.GetDouble(1) + "','" + dr1.GetString(2) + "') ", conn2);
// SqlCeDataReader dr2 = cmd2.ExecuteReader();
cmd2.ExecuteNonQuery();
}
}
//-------------------------------------------------------------------
I would take a look at the SqlBulkCopy Class:
Lets you efficiently bulk load a SQL
Server table with data from another
source.
BTW: In your code above, selecting the entire bill_discount table is not really a good idea, especially if the table is large.
[Also, it appears you could perform a single TSQL statement rather than looping through each row and round-tripping to the database.]
This example should be of help: SqlBulkCopy - Copy Table Data Between SQL Servers at High Speeds - ADO.NET 2.0 New Feature
Let's start by make the code more readable. Here's the result:
SqlCeCommand getAllBills = new SqlCeCommand("select * from bill_discount", primaryConnection);
SqlCeDataReader allBillsReader = getAllBills.ExecuteReader();
while (allBillsReader.Read())
{
SqlCeCommand getBill = new SqlCeCommand("select * from bill_discount where bill_no = '" + allBillsReader.GetInt32(0) + "' and bill_shopdc = '" + allBillsReader.GetString(2) + "' ", secondaryConnection);
SqlCeDataReader billReader = getBill.ExecuteReader();
if (!billReader.Read())
{
SqlCeCommand addMissingBill = new SqlCeCommand("insert into bill_discount (bill_no, bill_value, bill_shopdc) values ('" + allBillsReader.GetInt32(0) + "', '" + allBillsReader.GetDouble(1) + "', '" + allBillsReader.GetString(2) + "')", secondaryConnection);
addMissingBill.ExecuteNonQuery();
}
}
Disposable objects must be disposed. Let's do it.
Let's also remove SQL Injections.
Finally, let's optimize the second query: you don't need to select something and executing the reader if you just want to check if the value exists in the database.
using (SqlCeCommand getAllBills = new SqlCeCommand("select bill_no, bill_value, bill_shopdc from [bill_discount]", primaryConnection))
{
using (SqlCeDataReader allBillsReader = getAllBills.ExecuteReader())
{
while (allBillsReader.Read())
{
using (SqlCeCommand getBill = new SqlCeCommand("if exists(select * from [bill_discount] where [bill_no] = #billNumber and bill_shopdc = #billShop) select 1 else select 0", secondaryConnection))
{
getBill.Parameters.AddWithValue("#billNumber", allBillsReader["bill_no"]);
getBill.Parameters.AddWithValue("#billShop", allBillsReader["bill_shopdc"]);
bool billExists = Convert.ToBoolean(getBill.ExecuteScalar());
if (!billExists)
{
using (SqlCeCommand addMissingBill = new SqlCeCommand("insert into [bill_discount] ([bill_no], [bill_value], [bill_shopdc]) values (#billNumber, #billValue, #billShop)", secondaryConnection))
{
addMissingBill.Parameters.AddWithValue("#billNumber", allBillsReader["bill_no"]);
addMissingBill.Parameters.AddWithValue("#billValue", allBillsReader["bill_value"]);
addMissingBill.Parameters.AddWithValue("#billShop", allBillsReader["bill_shopdc"]);
int countAffectedRows = addMissingBill.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "The data was not inserted.");
}
}
}
}
}
}
So here we are.
Now, it's still a low performance solution. To be more effective, you might want to do the same thing in a single SQL query with joins. Since two tables are probably situated on different servers, you may look at linked servers: a feature that enables to execute a single query over several tables from several servers.
I see you are using SqlCe, which has number of limitations when inserting bulk data. The main limitation is the actual SqlCe Engine. You can however bypass this by using direct table inserts:
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.TableDirect;
command.CommandText = TABLE_NAME_IN_SQL;
using (var rs = command.ExecuteResultSet(ResultSetOptions.Updatable))
{
var rec = rs.CreateRecord();
rec.SetInt32(0, value0); // the index represents the column numbering
rec.SetString(1, value1);
rec.SetInt32(2, value2);
rs.Insert(rec);
}
}

C# SQL Columns into ComboBox

My SQL query isn't dropping anything into the combobox. The connection seems to be made but the while loop doesn't seem to work. Can anybody tell me what it wrong?
string sqltable = ("dbo.SLTDS_C"+id+"_table");
SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security);
con.Open();
string sqldatapull = ("select name from syscolumns where id = object_id('" + sqltable + "') order by name asc");
SqlCommand cmd = new SqlCommand(sqldatapull, con);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
sqldatapull = dr[0].ToString();
comboBox1.Items.Add(sqldatapull);
}
dr.Close();
con.Close();
Correction code:
string sqldatapull = ("select name from syscolumns where id = object_id('" + sqltable + "') order by name asc");
It's because you're including dbo. as part of the table name. If you run
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
You will see that the table names have no schema in the TABLE_NAME column.

Categories

Resources