Missing Required Parameter in Parameterized Query? - c#

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.

Related

C# write select from mysql to variable

I have a big problem with save variable from select in mysql.
I wrote the following code:
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string query_date = "SELECT computer_name from wp_users where user_login = #login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
reader = command2.ExecuteReader();
while (reader.Read())
{
string ColumnName = (string)reader["computer_name"];
}
cnn.Close();
I tried a lot of commands like ExecuteReader , ExecuteNonQuery , ExecuteScalar. but none of them worked and I am getting the same error:
Really don't know what is wrong here I searched a lot and didn't find a solution of any form. Please help.
EDIT 1
I just did how you wrote and i did this :
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string query_date = "SELECT computer_name from wp_users where user_login = #login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
DataTable table = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command2);
adapter.Fill(table);
// This is the important line
string result = table.Rows[0].ToString();
cnn.Close();
Its the same error as earlier but another place. What's going on here... just don't know.
Additional information mean in english : The key is not present in the dictionary
EDIT 2
The funniest is when i just try to update with code :
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string upd = "UPDATE w_users Set computer_name = CURRENT_DATE where user_login = #login";
MySqlCommand command2 = new MySqlCommand(upd, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
DataTable table = new DataTable("ResultTable");
SqlDataAdapter adapter = new MySqlDataAdapter(command2);
adapter.Fill(table);
cnn.Close();
And this works fine without any errors just update my table... What's the point of it
EDIT 3
I jutr try used to ExecuteScalar() and still i have the same error :
The solution is simple:
Updating mysql.data.dll to the newest version fixed it (https://dev.mysql.com/downloads/connector/net/6.9.html).
This exception wants to tell you, that there is no matching key in your resultset. Keys are case sensitive. Have you tried to spell your column name with all uppercase letters: (string)reader["COMPUTER_NAME"]?
Databases tend to return the column names in uppercase, even though you selected the column name in lower case.
If you have the MySqlDataAdapter, try if the following code works for you:
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
string query_date = "SELECT computer_name AS `computer_name` FROM wp_users WHERE user_login = #login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
DataTable table = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command2);
adapter.Fill(table);
// This is the important line
string result = table["computer_name"];
cnn.Close();

Storing multiple values from an SQL select statement

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

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;

Get data in a .dbf file using c#

How can I get the data in a .dbf file using c#??
What I want to do is to read the data in each row (same column) to further process them.
Thanks.
You may create a connection string to dbf file, then using OleDb, you can populate a dataset, something like:
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=directoryPath;Extended Properties=dBASE IV;User ID=Admin;Password=;";
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + fileName;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
Later you can use the ds.Tables[0] for further processing.
You may also check this article Load a DBF into a DataTable
I found out the accepted answer didn't work for me, as the .dbf files I'm working with are nested in a hierarchy of directories that makes the paths rather long, which, sadly, cause the OleDbCommand object to throw.
I found a neat little library that only needs a file path to work. Here's a little sample adapted from the examples on its GitHub page:
var file = "C:\\Path\\To\\File.dbf";
using (var dbfDataReader = new DbfDataReader(file))
{
while (dbfDataReader.Read())
{
var foo = Convert.ToString(dbfDataReader["FOO"]);
var bar = Convert.ToInt32(dbfDataReader["BAR"]);
}
}
For 64 bit systems I used the Microsoft ACE OLEDB 12.0 data provider, for that provider to work you have to install Microsoft's Access Database Engine 2010
So it looks a lot like the accepted answer but with the provider changed:
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;";
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + fileName;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}

Using a existing connection in a Script Component (SSIS)

I have am OLEDB Connection configured in the connection managers and I want to use it in a SCRIPT. The script needs to call a stored proc and then create buffer rows. I have added the connection to the connections available to the script and this is my code.
Boolean fireagain = true;
SqlConnection conn = new SqlConnection();
conn = (SqlConnection)(Connections.Connection
.AcquireConnection(null) as SqlConnection);
SqlCommand cmd = new SqlCommand();
conn.Open();
ComponentMetaData.FireInformation(
0, "Script", "Connection Open", string.Empty, 0, ref fireagain);
cmd.Connection = conn;
cmd.CommandText = "up_FullTextParser_select" ;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Phrase", DbType.String).Value = Row.Keywords;
cmd.Parameters.AddWithValue("SpecialTerm", DbType.String).Value = "Exact match";
cmd.Parameters.AddWithValue("StopListId", DbType.Int32).Value = 0;
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TermsBuffer.AddRow();
TermsBuffer.Term = rdr[0].ToString();
}
conn.Close();
Anyway, it seems to fail on the AcquireConnection. Am I converting this wrong? Should I be using a different way to using the connections defined outside the script?.
You cannot cast an OLEDB connection to SqlConnection object. You must use the OleDbConnection object. See the example - http://blogs.msdn.com/b/mattm/archive/2008/08/22/accessing-oledb-connection-managers-in-a-script.aspx
This MSDN example implies that you using AcquireConnection incorrectly.
You need to use a managed connection provider.
If you insist on using an OLEDB connection, you cannot use AcquireConnection but you can extract the connection string and then use it to create an OLEDB connection:
string connstr = Dts.Connections["my_OLEDB_connection"].ConnectionString;
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(connstr);
This may not work if the connection string is created via an expression of some sort.
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
datatable dtExcelData = new datatable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();

Categories

Resources