How to use SQL parameters with NpgsqlDataAdapter? - sql

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.

Related

I wrote an SQL SELECT statement that returns the entire table data rather then just the results that match my search

I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}

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

Fill Datatable with list member, if it matches a SQL select

I have a list of numbers and names. I would like to search through a database and find if the number matches my sql select. if it does I need to fill it to the datatable along with the name. Then foreach row in the datatable write that to another list. I'm having trouble filling the name to the datatable as well because I'm not using it in the SQl select as a parameter.
DataTable dt = new DataTable();
try {
using (SqlConnection conn = getconnection()) {
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandTimeout = 5000;
string select = #"SELECT NBR
FROM People
where ID in (15,17) and NBR=Nbr and ACCEPTED=0";
foreach (Fields f in Members) {
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Nbr", f.nbr);
cmd.CommandText = select;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//if f.nbr matches sql select fill it to datatable how can I fill dt with f.name as well?
adapt.Fill(dt);
}
}
foreach (DataRow row in dt.Rows) {
Fields f1 = new Fields();
f1.nbr= Convert.ToInt64(row["NBR"]);
// f1.name=Convert.ToString(row["Name"]????
Not.Add(f1);
}
use
string select = #"SELECT NBR, Name
FROM People
where ID in (15,17) and NBR=#Nbr and ACCEPTED=0";

Remove repeated values from dataGridViewComboBoxColumn

I use DataGridViewComboBoxColumn to make a ComboBox in DataGridView but my ComboBox isn't good enough. I need my ComboBox to not have repeated values on it. This is an example:
Apple
Blackberry
Chrome
Apple
I want to remove the values that appear more than one time. How can I do that?
This is my code:
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
Dataset data = new Dataset();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string path = "Data Source = "+".\\"+"test.accdb";
string conStr = "Provider = Microsoft.ACE.OleDb.12.0;"+#path;
conn.Open();
string sql = "SELECT * FROM Table1;"
cmd = new OleDbCommand(sql,conn);
adapter = new OleDbDataAdapter(cmd);
data = new Dataset();
adapter.Fill(data,"Table1");
DataGridViewComboBoxColumn testcolumn = new DataGridViewComboBoxColumn();
testcolumn.Name = "test na ja";
testcolumn.Datasource = data.table[0];
testcolumn.ValueMember = "Remedy";
testcolumn.DisplayMember = "Remedy";
dataGridview1.Columns.Add(testcolumn);
conn.Close()
change the SELECT statement to return distinct values of remedy:
string sql = "SELECT DISTINCT remedy FROM Table1;"
and if you want it ordered:
string sql = "SELECT DISTINCT remedy FROM Table1 ORDER BY remedy ASC;"
or
string sql = "SELECT DISTINCT remedy FROM Table1 ORDER BY remedy DESC;"
As well as applying the distinct statement to your SQL it is possible to apply a distinct to the original DataTable when creating a second table as shown below (with a unit test and helper classes included that I used to prototype this).
I've added a comment below to highlight the line where the distinct is applied - what you use is the .ToTable() method which takes the Boolean parameter Distinct to specify only return distinct rows.
[TestMethod]
public void CreateDistinctDataTable()
{
DataTable originalTable = CreateDataTable();
AddDataToTable("Fred", "Bloggs", originalTable);
AddDataToTable("Fred", "Bloggs", originalTable);
AddDataToTable("John", "Doe", originalTable);
// This is the key line of code where we use the .ToTable() method
DataTable distinctTable = originalTable.DefaultView.ToTable( /*distinct*/ true);
// The original table has two rows with firstname of Fred
Assert.AreEqual(2, originalTable.Select("firstname = 'Fred'").Length);
// The new table only has one row with firstname of Fred
Assert.AreEqual(1, distinctTable.Select("firstname = 'Fred'").Length);
}
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
private void AddDataToTable(string firstname, string lastname, DataTable myTable)
{
DataRow row = myTable.NewRow();
row["firstname"] = firstname;
row["lastname"] = lastname;
myTable.Rows.Add(row);
}
One additional thought is I would suggest not selecting * from your table in the SQL statement. This can have performance implications down the track if more columns are added (particularly things like blobs) and could also mean you get columns that break the distinct nature of your query.

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)