how to pass dynamic value with in sql query - c#

int i = int.Parse(rid);
SqlConnection thisconnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\lagenius\JIvandhara ngo\JIvandhara ngo\ngo.mdf;Integrated Security=True;User Instance=True");
thisconnection.Open();
string st = ("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = 4");
DataSet thisdataset = new DataSet();
//string cmdtext = "select * from receipt_info where receipt_no =='" + i + "'";
SqlCommand cmd = new SqlCommand(st, thisconnection);
SqlDataAdapter data_ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
data_ad.Fill(dt);

string st = ("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no =" + i);

First, you should rewrite your statement using parameter
string st = "select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = #Receipt_Number";
And when you've created your SqlCommand - you should add parameter #Receipt_Number to it
cmd.Parameters.Add("#Receipt_Number", SqlDbType.Int);
cmd.Parameters["#Receipt_Number"].Value = i;

When sending parameterized queries, you should use SqlParameter. An example of how to use them are available at http://www.dotnetperls.com/sqlparameter
Basically you structure your query with placeholders, and fill them using the SqlCommands Parameters property.
int searchId = 4;
string connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\lagenius\JIvandhara ngo\JIvandhara ngo\ngo.mdf;Integrated Security=True;User Instance=True"
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (SqlCommand command = new SqlCommand(
"select receipt_no, name, rupees, pay_by, date " +
"from receipt_info where receipt_no = #Id", connection))
{
command.Parameters.Add(new SqlParameter("Id", searchId));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}

string st = string.Format("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = {0}",i);

Related

Out of Range Error while accessing date from SQL Server

I want to fetch the maximum value of date from the table. But I always get an 'OutofRangeException' error. I changed my query several times.
Due_Date column has date data type
Due_Date_Sample is a string var
Due_Date_var is a DateTime var
My code:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') FROM Transactions WHERE Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}
You need to give an alias to the selected value, e.g.: FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date
You can do this:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}

How to construct Dynamic #Para statement?

How to construct dynamic select statement with two different parameters.
My code works fine without parameter but if i like to convert it in parameters.
If i convert code with #VehiNo and #CustName.
Please check comments in code.
using (SqlConnection conn = new SqlConnection(dbConn))
{
if (txtSearchVehicleNo.MaskCompleted)
{
sqlString = "Select * From Master Where VehiNo = '" + txtSearchVehicleNo.Text + "'"; // here i convert with #VehiNo
}
else if (!string.IsNullOrWhiteSpace(txtSearchMemberName.Text))
{
sqlString = "Select * From Master Where CustName = '" + txtSearchMemberName.Text + "'"; // here i convert with #CustName
}
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = CommandType.Text;
// How to use following 2 in condition
//cmd.Parameters.AddWithValue("#VehiNo", txtSearchVehicleNo.Text);
//cmd.Parameters.AddWithValue("#CustName", txtSearchMemberName.Text);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtMember.Load(reader);
}
}
How about this:
using (SqlConnection conn = new SqlConnection(dbConn))
{
using (SqlCommand cmd = new SqlCommand())
{
string sqlString = string.Empty;
if (txtSearchVehicleNo.MaskCompleted)
{
sqlString = "Select * From Master Where VehiNo = #VehiNo;";
cmd.Parameters.AddWithValue("#VehiNo", txtSearchVehicleNo.Text);
}
else if (!string.IsNullOrWhiteSpace(txtSearchMemberName.Text))
{
sqlString = "Select * From Master Where CustName = #CustName;";
cmd.Parameters.AddWithValue("#CustName", txtSearchMemberName.Text);
}
cmd.Connection = conn;
cmd.CommandText = sqlString;
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtMember.Load(reader);
}
}

Pass String into SQL Query from Textbox

Background
I've written a function that retrieves data using a SQL query and then outputs that data to a label. At the moment the search string is hard coded to "1002". The function is fired on a button click event.
Question
How do I pass data into my SQL query from a textbox so my search string is the contents of the text box, instead of 1002?
Code
private void getInfoStationID()
{
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = 1002";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, ConnStr);
DataSet question = new DataSet();
Adpt.Fill(question);
foreach (DataRow dr in question.Tables[0].Rows)
{
nameTtb.Text += question.Tables[0].Rows[0]["stationname"].ToString();
}
}
Change the query to:
string constring = #""; // Declare your connection string here.
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationId";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand command = new SqlCommand(SQL ,con);
and then you have to add parameter to the command object like this:
command .Parameters.Add("#StationId",SqlDbType.NVarChar).Value = textbox.Text;
Now you might be wondering why I have used parameters in the query. It is to avoid SQL Injection.
DataSet ds = new DataSet();
SqlDataAdapter adb = new SqlDataAdapter(command);
adb.Fill(ds);
con.Close();
And now you can iterate like this...
foreach (DataRow row in ds.Tables[0].Rows)
{
}
And you have to initialise the connection object and pass your connection string in it.
You can change your SQL string to use a variable, like #StationID, then add the variable to the query from textbox.text
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationID";
SqlCommand cmd = new SqlCommand;
cmd.CommandText = SQL;
cmd.CommandType = CommandType.Text;
cmd.Connection = ConnStr;
cmd.Parameters.AddWithValue("#StationID", Textbox1.Text);
da = new SqlDataAdapter(cmd);
DataSet nds = new DataSet();
da.Fill(nds);
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
string SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #stationID";
SqlCommand command = new SqlCommand(SQL, ConnStr);
command.Parameters.Add(new SqlParameter("#stationID", SqlDbType.Int));
command.Parameters["#stationID"].Value = textbox.Text;

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

insert data to table based on another table C#

I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.

Categories

Resources