Storing multiple values from an SQL select statement - c#

I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated

Related

Want to Fill Text Box With Access Data

In C# I want to use access data to fill my textBox I Am using ADO.Net To connect to access.So far I've got this:
OleDbConnection con = new OleDbConnection(Price.constr);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=con;
cmd.CommandText = "select * from Table1";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Price.constr is my connection String.
I want to fill textBox1 with the data in the Price Column Where my row ID = 1.(For Example)
If you want to read only one record from your table then there is no need to return the whole table and use an adapter to fill a datatable. You can simply ask the database to return just the record you are interested in.
string cmdText = "select * from Table1 WHERE ID = 1";
using(OleDbConnection con = new OleDbConnection(Price.constr))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
textBox1.Text = reader["Price"].ToString();
else
textBox1.Text = "No record found";
}
}
I have enclose the connection, command and reader in an using statement because these are disposable objects and it is a good practice to destroy them when you have finished to use them. (In particular the connection could cause problems if you don't dispose it)
Notice also that I have used the constant 1 to retrieve the record. I bet that you want this to be dynamic and in this case I suggest you to look at how to PARAMETRIZE your queries. (Don't do string concatenations)

Speedup ExecuteReader in C#

I'm using a C# SqlDataReader in many loops. Unfortunately I can't read the whole table and store the data in a list. So I have to create a SqlDataReader again and again. Once the SqlDataReader is created, its very fast. But the creation of the SqlDataReader via ExecuteReader takes too much time.
Is there any possibility to improve the creation time of the SqlDataReader?
I'm using .NET 4.5.1 and SQL Server 2008.
string sql = "select CURRENT_TIMESTAMP";
var connection = Connections.Get();
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.CommandTimeout = 0;
var reader = sqlCommand.ExecuteReader(CommandBehavior.Default);
Thanks
Michael
string conString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("select TOP 50000 * from users", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
please use DataTable and SqlDataAdapter to read the data
Instead of using ExecuteReader

Missing Required Parameter in Parameterized Query?

I am getting the following error trying to execute the code below
No Value Given For One Or More Required Parameters.
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = "SELECT [FUNCTION],[NAME] from [Sheet1$] WHERE [FUNTION] = ?";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connString;
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("?", paraName);
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd);
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
OleDbCommand does not support named parameters (see the docs). What you need to do is something like:
cmd.Parameters.Add(new OleDbParameter { Value = paraName });
Edit: I haven't tried it, but I suppose it might be possible to use your above code and pass null as the name argument...
James, I can see that you are trying to parametrize as you would with SQL. However OleDb wouldn't follow the exact pattern. In OleDb you can simply put question marks in your sql sentence and fill them up later using Parameter.Add().value which is quite straight forward.
As MSDN reference points out:
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text.
I have rewritten your code in the way it should look like
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = string.Format("SELECT [{0}],[{1}] from [{2}] WHERE [{0}] = ?", strFunction, strName, strSheetName);
conn.ConnectionString = connString;
using (OleDbConnection conn = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameter.Add("#Param1", OleDbType.VarChar).Value = paraName; // paraName or any value you wish.
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd); //or cmd.ExecuteNonQuery(); in Insert sql commands.
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Note, You should put your OleDbConnection inside the using statement rather than your OleDbCommand.
I haven't tested it and it may contain some minor error. Other than that punch it there and press play (F5).
You can find more on OleDb parametrization from OleDbCommand.Parameters Property
Good luck and let us know what happens.

How use WHERE in SqlDataAdapter in C#

How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

loading a data table into a data grid view problems

I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.
SqlConnection DBConnection = new SqlConnection(ConnectionString);
//Opens the connection
DBConnection.Open();
//Creates a string to hold the query
string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";
//Creates an SQLCommand object to hold the data returned by the query
SqlCommand queryCommand = new SqlCommand(query, DBConnection);
//Uses the aforementioned SQLCommand to create an SQLDataReader object
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Creates a DataTable to hold the data
DataTable dataTable = new DataTable();
//This part actually loads the data from the query into the table
dataTable.Load(queryCommandReader);
dgvOutput.DataSource = dataTable;
The other example:
using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
{
DataTable Table = new DataTable();
newDA.Fill(Table);
dgvOutput.DataSource = Table;
}
You might try this or something similar:
SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text;
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;

Categories

Resources