How to pass integer variable in sql query - sql

int no = FormView1.PageIndex;
Query:-
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);

You have to add a parameter:
int no = FormView1.PageIndex;
SqlCommand cmd =
new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
// Set the parameter up before executing the command
cmd.Parameters.Add("#no", SqlDbType.Int);
cmd.Parameters["#no"].Value = no;

You need to add a SqlParameter to the SqlCommand:
int no = FormView1.PageIndex;
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
cmd.Parameters.AddWithValue("#no", no);

use an array of System.Data.SqlClient.SqlParameter
SqlCommand cmd(...);
SqlParameter[] inQueryParameters = ...;
cmd.Parameters.AddRange(inQueryParameters);

Use SqlParameters. See the example below.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

You can use this code:
SqlCommand ageCom = new SqlCommand("select age_phase from PatintInfo where patient_ID=#ptn_id", con);
ageCom.Parameters.Add("#ptn_id",SqlDbType.Int).Value=Convert.ToInt32(TextBox1.Text);
It had worked in my program correctly.

Related

Oracle parameterized update query c#

It should work but it doesn't.
I have referred others but couldn't find the reason.
OracleCommand cmd = con.CreateCommand();
var query = $#"UPDATE Customer SET ContactName = :ct WHERE CustomerID = :id";
cmd.CommandText = query;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":id", OracleDbType.Varchar2, "bbb1", System.Data.ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter(":ct", OracleDbType.Varchar2, "Joon", System.Data.ParameterDirection.Input));
var rst = cmd.ExecuteNonQuery();
Thanks in advance.
Joon
I found why it didn't update table.
To make it work I added parameters in the order of the query parameter and found it works. But I still do not understand why the order of adding parameters is so important to make it work.But the thing clear is that it is working when I make it like this:
OracleCommand cmd = con.CreateCommand();
var query = $#"UPDATE Customer SET ContactName = :ct WHERE CustomerID = :id";
cmd.CommandText = query;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":ct", OracleDbType.Varchar2, "Joon", System.Data.ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter(":id", OracleDbType.Varchar2, "bbb1", System.Data.ParameterDirection.Input));
var rst = cmd.ExecuteNonQuery();
Thanks everybody who paid attention on it.
Joon
In order to avoid the order declaration, you can use BindByName:
OracleCommand cmd = con.CreateCommand();
cmd.BindByName = true; // Just add this
...

How to use SQL parameters with NpgsqlDataAdapter?

Is it possible to use parameters together with NpgsqlDataAdapter, as I can do with NpgsqlCommand:
string sql = "SELECT * FROM tbl_student WHERE name = #val";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("#val", name);
I have this code, which displays the information about the students i a gridview:
string sql = "SELECT * FROM tbl_student WHERE studentname = '" + name + "'";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds); // filling DataSet with result from NpgsqlDataAdapter
dt = ds.Tables[0]; // select select first column
GridView1.DataSource = dt; //connect grid to DataTable
GridView1.DataBind();
My question is: can I somehow use parameters (as in the example above) instead of using '" + name + "' in the SQL?
I have learned always to use parameters, is it also necessary when using NpgsqlDataAdapter?
Thank you.
I used to have the same question and this is what I came up with:
string sql = "SELECT * FROM tbl_student WHERE studentname = #param";
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
command.Parameters.Add("#param", textBox_studentname.Text); //add the parameter into the sql command
DataTable dt = new DataTable();
//load the DataReader object of the command to the DataTable
dt.Load(NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection));
GridView1.DataSource = dt;
You could read this and this.

How to use the ID of an item after loading combobox from database.?

SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select ID,Name from Employee";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cbSupportID.DataSource = ds;
cbSupportID.DisplayMember = "Name";
cbSupportID.ValueMember = "ID";
cbSupportID.Enabled = true;
cmd.ExecuteNonQuery();
con.Close();
now i want use the id of items in my form to process..Plzz tell me the best solution with code.
now you simply retrieve your selected combobox ID value using
cbSupportID.SelectedValue
eg.
If cbSupportID.SelectedIndex <> -1 Then
textBox1.Text = cbSupportID.SelectedValue.ToString()
End If
You can also access other useful properties like SelectedIndex (starting from 0...) or SelectedItem.
check here: http://msdn.microsoft.com/en-US/library/system.windows.forms.listcontrol.selectedvalue(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

SQL Query help requested

I am trying to use the following query
Dim sqlQry As String = "SELECT * FROM tblTest where Name=#NM and Rank=#RN"
Then I fill my dataadapter by
Dim dAdt As New SqlDataAdapter(sqlQry, conStr)
But do not know where to put the parameters that I have set after where clause.
You can use the parameters like this:
Dim adapter As SqlDataAdapter = New SqlDataAdapter()
' Create the SelectCommand.
Dim command As SqlCommand = New SqlCommand("SELECT * FROM tblTest where Name=#NM and Rank=#RN", connection)
' Add the parameters for the SelectCommand.
command.Parameters.Add("#NM", SqlDbType.NVarChar, 15)
command.Parameters.Add("#RN", SqlDbType.NVarChar, 15)
adapter.SelectCommand = command
Check this MSDN Document
Create a parameter
SqlParameter param = new SqlParameter();
param.ParameterName = "#RN";
param.Value = inputCity;
Then add the param to your Sql Command.
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(param);
If I understand what you're asking, you need to create an instance of an SqlCommand and use your sqlQry with that. Then use SqlCommand.Parameters.Add() or SqlCommand.Parameters.AddWithValue() to add your parameters. Initialize your SqlDataAdapter with the SqlCommand instead of the String you've created.
Using connection As New SqlConnection(conStr)
Dim command As New SqlCommand(sqlQry, connection)
command.Parameters.Add("#NM", SqlDbType.NVarChar, 100).Value="Your Value"
command.Parameters.AddWithValue("#RN", "Your Value")
Dim adapter As New SqlDataAdapter(command)
adapter.Fill(dataSet)
Return dataSet
End Using

How to get a dataset value

New to VB.Net,
How to insert or select the dataset value.
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
cmd = New SqlCommand("Select * from '" & ds.Tables(0) & "' ", con)
mydatatable1.Load(dr3)
It was showing the error in '" & ds.Tables(0) & "', I want to get the dataset value
Need VB.Net Code Help
You have a reasonable idea right up until you get to the point where you are trying to create a second SqlCommand. That is, once you do the Fill, you already have the data in a table. You wouldn't run another select - you've already done that. You'd just reference the table that you want to use in the dataset.
If you want a data table you would do something like this (for VB, see below):
SqlDataAdapter myAdapter = new SqlDataAdapter(CommandText, con);
DataSet myDataset = new DataSet();
myAdapter.Fill(myDataset, "Table"); // "Table" is just a name, it can be anything.
mydatatable1 = myDataset.Tables[0]; // Get the table
Now, if you don't need a DataTable, per se, but just want to read from the query, you'd use a SqlDataReader:
cmd = new SqlCommand(CommandText, con);
// One or more params
cmd.Parameters.AddWithValue("#paramName", Value);
SqlDataReader nwReader = cmd.ExecuteReader();
Then just read from the nwReader:
while (nwReader.Read())
{
string field1Val = (string)nwReader["FieldName"];
etc...
}
Update: I don't know VB but here is what I think it would look like:
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
mydatatable1 = ds.Tables(0);
You may well be able to shorten this to get rid of the extra SqlCommand (assuming VB supports this SqlDataAdapater syntax like C#.
ada = New SqlDataAdapter("Select * from table1", con)
ds = New DataSet
ada.Fill(ds)
mydatatable1 = ds.Tables(0);
Good luck...
you can use Microsoft Enterprise Library for making easy this process. this library is a powerful library for working with datasets.
public async Task<ResponseStatusViewModel> GetAll()
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_GetAllEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
try
{
await connection.OpenAsync();
var reader = await command.ExecuteReaderAsync();
var dataSet = new DataSet();
dataSet.Load(reader, LoadOption.OverwriteChanges, new string[] { "Employee" });
reader.Close();
reader.Dispose();
var employees = new List<EmployeeModel>();
if (dataSet.Tables.Count > 0 && dataSet.Tables["Employee"] != null)
{
var employeeTable = dataSet.Tables["Employee"];
for (int i = 0; i < employeeTable.Rows.Count; i++)
{
var employeeRow = employeeTable.Rows[i];
employees.Add(new EmployeeModel
{
EmployeeID = Convert.ToInt32(employeeRow["EmployeeID"]),
EmployeeName = Convert.ToString(employeeRow["EmployeeName"]),
Address = Convert.ToString(employeeRow["Address"]),
GrossSalary = Convert.ToDouble(employeeRow["GrossSalary"]),
PF = Convert.ToDouble(employeeRow["PF"]),
TotalSalary = Convert.ToDouble(employeeRow["TotalSalary"])
});
}
}
responseStatusViewModel.Data = employees;
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
I think what you are looking for is
cmd = New SqlCommand("Select * from '" & ds.Tables(0).TableName & "' ", con)
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
cmd = New SqlCommand("Select * from '" & ds.Tables(0).TableName & "' ", con)
mydatatable1.Load(dr3)