i need to get more than one value from database sql - c#

I need to get 6 values from database and bind them to link button texts her is the code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string post = Request.QueryString["post"];
////string title = "nokia";
string date = DateTime.Now.ToShortDateString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
try
{
conn.Open();
//string str = "insert into Table1 (title , date_ ,www, cat) values (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
////string str = "INSERT INTO Table1 (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";
string str =
//"SELECT from table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee";
"SELECT table1.title FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";
SqlCommand objcmd = new SqlCommand(str, conn);
SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
da1.Fill(dt);
//DataRow dr = new DataRow();
//DataRow dr = ds.Tables[0].Rows[0];
foreach (DataRow dr in dt.Rows)
{
ml1.Text = dr[0].ToString();
ml2.Text = dr[1].ToString();
ml3.Text = dr[2].ToString();
ml4.Text = dr[3].ToString();
ml5.Text = dr[4].ToString();
ml6.Text = dr[5].ToString();
}
}
catch (Exception ex)
{
Label4.Text = "Failed to connect to data source";
}
finally
{
conn.Close();
}
}
}
ml is link button id

You are trying to assign 6 fields from the row returned to 6 different textboxes, but your select query asks for just one field. If you want more than one field returned then add their names to the select query (change fieldX to the appropriate field name).
string str = "SELECT title, field1, field2, field3, field4, field5 " +
"FROM table1 WHERE cat = 1 and datee=#dt ORDER BY datee DESC";
also do not use string concatenation to build the sql statement. Use always a parametrized query
SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("#dt", datee);
.....
this will avoid problem with formatting strings, date, numbers etc, but also the sql injection problem.
By the way, I hope that your code returns just one row because, as it stands now, if you have more than one row returned then only the one with the earliest date will be shown in the textboxes. (And if this is the case then the order by is useless). If you have more than one row returned then you should consider to bind the datatable to a GridView to show all records returned.

Related

Updating values from excel to database

I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.

DataAdapter Sql Query with parameters - c#

Code below is working properly and view all matches by search in column.
string sql = "SELECT car, model, year FROM store WHERE" + column + "LIKE " + search + "'";
Now adding parameters in query. Not working. It doesn't display search in column. Only display all rows in column, if search column of column ( 1 = 1)
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = "SELECT car, model, year FROM store WHERE #column like #search '";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + searchCars.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + searchCars.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
What could possible be the answer to get it search within specific column?
Change it as follows so as to not parameterize the column name:
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = string.Format("SELECT car, model, year FROM store WHERE {0} like #search", search.GetCombo());
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
// sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + search.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + search.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
Also, you've got an extra quote at the end of your query:
like #search '";
Please take a look at this
private static void Select() {
string cmdStr = "SELECT FirstName, LastName, Telephone FROM Person WHERE FirstName = #FirstName";
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(cmdStr, connection)) {
command.Parameters.AddWithValue("#FirstName", "John");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string output = "First Name: {0} \t Last Name: {1} \t Phone: {2}";
Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]);
}
}
}

How do I check Duplicate [duplicate]

This question already has an answer here:
how to i search if there is a same id in a database?
(1 answer)
Closed 6 years ago.
private void Add_Box_Click(object sender, EventArgs e)
{
string phoneNumber;
if (string.IsNullOrWhiteSpace(Id_Box.Text))// To check if the Id_box is empty or not
{
MessageBox.Show("Please Enter Your ID");// need to enter ID in order to save data
}
///////////////////////////////////////////check the Extension Box////////////////////////////////////////////////////////////////////////////////////
else
{
if (string.IsNullOrWhiteSpace(Ext_Box.Text))
{
phoneNumber = Phone_Box.Text;// if it is empty then it will only show the phone number
}
else
{
phoneNumber = Phone_Box.Text + "," + Ext_Box.Text; // show the phone number and the extension if there is something in the extension
}
///////////////////////////////////////////////////////////Save it to the Database///////////////////////////////////////////////////////
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Contact_List(Id, Name, Adress1, Adress2, City, Province, Postal_Code, Phone, Email)VALUES('" + Id_Box.Text + "','" + Name_Box.Text + "','" + Adress1_Box.Text + "','" + Adress2_Box.Text + "','" + City_Box.Text + "','" + Province_Box.Text + "','" + Code_Box.Text + "','" + phoneNumber + "','" + Email_Box.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Information Added", "Confirm");
/////////////////////////////////////Show new set of data after insert a new data/////////////////////////////////////////////////////////////
SqlCeCommand cmd2 = new SqlCeCommand("Select * from Contact_List;", con);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmd2;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
////////////////////////////////Empty The Box/////////////////////////////////////////////////////////////////////////////////////////////////
Id_Box.Text = String.Empty;
Name_Box.Text = String.Empty;
Adress1_Box.Text = String.Empty;
Adress2_Box.Text = String.Empty;
City_Box.Text = String.Empty;
Province_Box.Text = String.Empty;
Code_Box.Text = String.Empty;
Phone_Box.Text = String.Empty;
Ext_Box.Text = String.Empty;
Email_Box.Text = String.Empty;
}
}
This code will store Id, name, etc to the database. But when there is a same Id, i want to delete it. When i delete it both of the same Id will be deleted and i don't want that so is there anyway to check duplicate before it store it to the database?
I want to do something like this if possible :
if ( the values in id column == to the Id_textBox) {
MessageBox.Show("Duplicate ,PLease enter anotherId")
}
Possible?
Before executing your INSERT SQL statement, try running the SQL int ContactCount = (int)cmd.ExecuteScalar("SELECT COUNT(*) FROM CONTACT_LIST WHERE Id = '" + Id_Box.Text + "'")
If ContactCount > 0 then you can do the DELETE your suggesting.
Can I also recommend that you use a SQL UPDATE instead of DELETEing and INSERTing the same record.
Also, read-up on SQL Injection attacks. Building a SQL statement, like you're doing here, using the values input by a user leaves you exposed to that type of vulnerability.
First of all, like in all these answers: Don't use string concatenation but parametrized queries to prevent SQL-injection.
For your problem:
You can either do a
string query = "SELECT count(*) from ContactList Where id = #id";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = (int)cmd.ExecuteScalar();
if count > 0 the id already exists.
Or you can do a
string query "IF NOT EXISTS(SELECT count(*) from ContactList Where id = #id) INSERT INTO ContactList(Id, ...) VALUES(#id, ...)";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = cmd.ExecuteNonQuery();
count will then contain the number of rows affected, ie 0 if the value already existed, or 1 if it did not exist, but was newly inserted.

I want to restrict a user to insert his performnce only once per day

I wrote this code, but it allows users to enter their performance record more than once a day while what I want is for the user to only be able to do so once a day.
At first I wrote the condition like this: if (dt.Rows.Count < 0) but in this case only else part is working and user can not enter his record at least once..
protected void subtbtn_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=incible;Integrated Security=true");
connection.Open();
string sqlStatement = "SELECT * FROM prfrmnce where u_name='" + unamelbl.Text + "' and datetime ='" + Calendar1.TodaysDate + "'";
SqlCommand cmd1 = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd1);
sqlDa.Fill(dt);
if (dt.Rows.Count == 0)
{
// Open the database connection
string myConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=incible;Integrated Security=true";
SqlConnection con = new SqlConnection(myConnectionString);
con.Open();
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("Insert into prfrmnce(u_name,designatn,datetime,todaytask,tmrwplan) values(#uname,#dsgntn,#date,#twrk,#tmrwpln) ", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("#uname", UserName.Text);
cmd.Parameters.AddWithValue("#dsgntn", desigtxtbx.Text);
cmd.Parameters.AddWithValue("#twrk", tfortday.Text);
cmd.Parameters.AddWithValue("#tmrwpln", pfortmrw.Text);
cmd.Parameters.AddWithValue("#date", Calendar1.TodaysDate);
cmd.ExecuteNonQuery();
resultlebel.Text = "data added successfully";
//Close dbconnection
con.Close();
tfortday.Text = string.Empty;
pfortmrw.Text = string.Empty;
GridView1.DataBind();
}
else if (dt.Rows.Count > 0)
{
errorlabel.Text = "You have already submitted your today's performance";
}
}
I would guess this is a DateTime problem. DateTime is not a day, it has also hours, minutes, etc.
You should work with the date part of the date only.
So in your query,
change
and datetime ='" + Calendar1.TodaysDate + "'"
to
and cast(datetime as date) = '" + Calendar1.TodaysDate.Date + "'"
By the way, you should work with parameters, not string concatenation.
See msdn
Is this query correct...
string sqlStatement = "SELECT * FROM prfrmnce where u_name='" + unamelbl.Text + "' and datetime ='" + Calendar1.TodaysDate + "'";
The problem might be Calendar1.TodaysDate gives date and time so you will always get dt.Rows.Count as 0

Find data in database

I have an idea of what supposed to do just not exactly sure how to put it all together. I'm trying to search records in my data using a text box. I would like if the user didnt know the whole address just to be able to enter a portion of the address and still return records. If I enter the full address then a record returns. But if I just enter the first couple letters and search nothing returns.
Thanks
Here is what I have :
protected void btnFind_Click(object sender, EventArgs e)
{
string searchFor = txtFirstName.Text.Trim();
int results = 0;
string errorText = "No records found";
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Contacts.mdb");
conn.Open();
DataSet ds = new DataSet();
string cmd = "SELECT * FROM Contact WHERE Address LIKE '+searchFor ' ";
OleDbDataAdapter da = new OleDbDataAdapter(cmd, conn);
da.Fill(ds, "Search");
DataRow[] row;
DataRow dr;
row = ds.Tables["Search"].Select("Address='" + searchFor + "'");
results = row.Length;
if (results > 0)
{
dr = row[0];
txtFirstName.Text = dr["FirstName"].ToString();
txtLastName.Text = dr["LastName"].ToString();
txtEmail.Text = dr["Email"].ToString();
txtAddress.Text = dr["Address"].ToString();
txtPhone.Text = dr["Phone"].ToString();
}
else
{
lblError.Text = errorText;
}
conn.Close();
}
1. you are misusing single quotes in your query. you need to wrap up the string variables with single quotes.
2. you are not properly adding parameter in your query. you need to close parameter
with concatenation + operator
3. you need to use % for searching.
example : if you want to search in between you can use % before and after your search string
This
string cmd = "SELECT * FROM Contact WHERE Address LIKE '+searchFor ' ";
should be
string cmd = "SELECT * FROM Contact WHERE Address LIKE '%"+ searchFor +"%'";
You could try this code:
string cmd = "SELECT * FROM Contact WHERE Address LIKE '%"+ searchFor +"%'";

Categories