Prepared SELECT statement in .Net - c#

I can't understand what I am doing wrong, I can't seem to SELECT with a prepared statement. However I can INSERT with a prepared statement.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
cmd.fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
Any advice on this would be greatly appreciated!

To fill a DataSet you will need a DataAdapter.
Try this:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.SelectCommand = cmd;
dAdap.Fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}

You need to use SqlDataAdapter
DataAdapter represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database.
The SqlDataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source
Check the following syntax:
private static DataSet SelectRows(DataSet dataset,
string connectionString,string queryString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, connection);
adapter.Fill(dataset);
return dataset;
}
}

Related

C# Parameterized query - parameters not being replaced with set value

I'm passing a query and parameter from a WinForm to a database class. The
The code on the Form looks like this:
string selectedComp = "CPSI";
string catsQuery = "SELECT id, category, old_value, old_desc, new_value, new_desc, reference1, reference2 FROM masterfiles.xref WHERE company_name = '#company' ORDER BY category, old_value";
Db categoriesData = new Db();
dgvCategories.DataSource = categoriesData.GetData(catsQuery, selectedComp);
And in my database class my code to populate the datatable/set is this:
public DataTable GetData(string selectQuery, string selectedComp)
{
NpgsqlConnection conn = new NpgsqlConnection(connString);
DataSet ds = new DataSet();
NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn);
cmd.Parameters.Add(new NpgsqlParameter("#company", selectedComp));
//cmd.Parameters.AddWithValue("#company", selectedComp);
//cmd.Parameters.Add("#company", NpgsqlDbType.Text);
//cmd.Parameters["#company"].Value = selectedComp;
try
{
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
conn.Close();
da.Fill(ds);
return ds.Tables[0];
}
}
But putting a breakpoint at NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);, selecctQuery hasn't changed - the '#company' is still in the query.
What am I missing?
The root problem is that you're passing the query to the data adapter instead of the command. Change
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
to
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
I would also use using to dispose of all objects, and don't close the connection until the dataset is filled:
using(NpgsqlConnection conn = new NpgsqlConnection(connString))
using(NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn))
{
cmd.Parameters.Add(new NpgsqlParameter("company", selectedComp));
conn.Open();
using(NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
}
conn.Close();
return ds.Tables[0];
}

Fill DataTable from Oracle Database Table - C#

I have successfully built connection string and able to populate table data when the database is Access as:
DataTable results = new DataTable();
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
OleDbCommand cmd = new OleDbCommand("SELECT * from TABLE_A", thisConnection); //EDIT : change table name for Oracle
thisConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
I am new to Oracle though. Can somebody mention what changes to make in above code for Oracle database?
You can try this;
OracleConnection conn = new OracleConnection("Your Connection string");
//Open the connection to the database
conn.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("your select query");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}

Dataset filter method

Here is my code,
Conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = " mst_remote_station_id Like'*9001*'";
Here I am getting Complete row for id 9001. I need only one column value for this id.
DataRow[] rows = ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
You can do it this way also if you need only one row just select it in the initial query.
Also you should Dispose the SqlDataAdapter after using it ! You can do it with using block
Conn.Open();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
using(SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(ds);
}
ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
I don't know if the connection is global but it is bad practice to use global connection, you have connection pool so use separate connection for every query.

OleDB Parameters

I have this access db that I have a ddl for the state name and a ddl for the year. I have a gridview that I'd like to pass the value of the state drop down list into where clause. Obviously if I could use sql with the named parameters I would but this is what I'm stuck with and not sure exactly how to format it correctly.
the drop down list is name ddlStates. In the parameters I've tried
mycommand.Parameters.Add("#ddlStates")
here is the data set
public DataSet GetData()
{
DataSet ds;
using (OleDbConnection myConnString = new OleDbConnection())
{
myConnString.ConnectionString = connString;
using (OleDbCommand myCommand = new OleDbCommand())
{
myCommand.CommandText = "select * from tblTest where location = ?";
myCommand.Parameters.Add();
myCommand.Connection = myConnString;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = myCommand;
ds = new DataSet();
da.Fill(ds, "Grades");
}
}
return ds;
}
}//ends get data dataset
1.you need to open your connection
2.you can add the parameter as follows
public DataSet GetData()
{
DataSet ds;
using (OleDbConnection conn = new OleDbConnection(connString))
{
string query= "select * from tblTest where location = ?";
using (OleDbCommand myCommand = new OleDbCommand(query, conn))
{
myCommand.Parameters.AddWithValue("#ddlStates", <your value>);
conn.Open();
using (OleDbDataAdapter da = new OleDbDataAdapter(myCommand, conn))
{
ds = new DataSet();
da.Fill(ds, "Grades");
return ds;
}
}
}
}
myCommand.Parameters.AddWithKey("location", this.ddlStates.SelectedValue);
That assumes that the data type of the location column is textual. If it's numeric or something else then convert the SelectedValue to the appropriate data type first.

How I Reload Datagridview data while insert or update data in .net form application and database is in access database?

I have a desktop application project. In entry page a datagridview shows the existing items in database. Now when I entry new Item I want to insert it directly in datagridview. That mean I want to reload/refresh datagridview. My database is in MS Access.
private DataTable GetData()
{
DataTable dt = new DataTable();
//using (SqlConnection con = new SqlConnection(conn))
using (OleDbConnection con=new OleDbConnection(conn))
{
OleDbCommand cmd = new OleDbCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
//SqlCommand cmd = new SqlCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
con.Open();
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
return dt;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
con.Open();
//SqlCommand cmd;
try
{
string query = "insert into GroupDetails (ID,Name) values(#ID,#Name)";
// cmd = new SqlCommand(query,con);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#ID",txtID.Text);
cmd.Parameters.AddWithValue("#Name",txtName.Text);
int i = cmd.ExecuteNonQuery();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
}
}
[Note: When I use sql database then it works fine.]
The dbDataAdapterClass (the one that OleDbDataAdapter inherits from) has a SelectCommand, UpdateCommand and InsertCommand. These are responsible for select, update, and insert when you explicit call any of the methods (for example update ;) ). Since in your code, you never provide the command that explain how to do the update, the dataadapter doesn't know how to do it.
so fulfill the requirements, adding an update command to the adapter.
dataadapter = new OleDbDataAdapter(sql, connection);
Add below code after above line, OleDbCommandBuilder will generate commands for you.
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
This tutorial should help you out.

Categories

Resources