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();
Related
i am making a program in visual studio code with C#, it is a paid program so it needs an hwid system. Basically i want it to check if your computer HWID exists in the HWID table in my users database. But it says it can't connect to the database. Can you help me? This is my code.`
string connectionString = "Server=SomeServer;Database=i got you this is notthe real database;User ID=same;Password=same for password;";
MySqlConnection mydbCon = new MySqlConnection(connectionString);
mydbCon.Open();
MySqlCommand command = mydbCon.CreateCommand();
command.CommandText = "SELECT * FROM yourTable WHERE hwid = GetHDDSerial";
IDataReader reader = command.ExecuteReader();
`
It could be that the connection string isn't formatted the way the MySQL connector wants it. The MySQL documentation shows "uid" instead of User, and "pwd" instead of Password. https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-connection-string.html
This should do what you need:
string connectionString = "Server=SomeServer;Database=i got you this is notthe real database;User ID=same;Password=same for password;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
string sql = "SELECT * FROM yourTable WHERE hwid = #val1";
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Parameters.AddWithValue("#val1", "GetHDDSerial");
connection.Open();
using (MySqlDataAdapter adapter = new MySqlDataAdapter())
{
using (DataSet ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
// Do something here. You can access the data like this:
// row["Id"] or whatever your field names are.
// int id = (int) row["Id"];
// Of course, I don't know your field names, so you'll have to complete this.
}
}
}
}
}
}
I'm trying to get values out of my database into my Listbox, I currently send all my results into a new object called Results
I want my listbox to show something like this:
Title(1)(enter)
Url(1)(enter)
Title(2)(enter)
Url(2)(enter)
and so on
It currently still gives an error at OleDbDataReader reader = command.ExecuteReader(); but I have no idea why.
This is the exact code
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = connection;
cmd1.CommandText = "SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '" + Convert.ToString(lbzoektermen.SelectedItem) + "';";
OleDbDataReader reader1 = cmd1.ExecuteReader();
if(reader1.Read())
{
resultaatid = Convert.ToInt32(reader1["ZoekcriteriaID"]);
}
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT Titel, Webadress from Resultaat WHERE ZoekriteriaID = '"+ resultaatid +"';";
OleDbDataReader reader = command.ExecuteReader();
lbresultaten.Items.Clear();
List<Results> resultaten = new List<Results>();
while(reader.Read())
{
Results result = new Results();
result.url = Convert.ToString(reader["Webadress"]);
result.titel = Convert.ToString(reader["Webadress"]);
resultaten.Add(result);
}
foreach(Results result in resultaten )
{
lbresultaten.Items.Add(result.titel);
lbresultaten.Items.Add(result.url);
}
I hope someone could help me,
Kind Regards,
Martijn
Your problem probably lays in your where clause:
SELECT ZoekcriteriaID from Zoekcriteria WHERE **ZoekCriteria**
It should be a column name, not a table name.
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.
I am trying to use MYSQL select query with c#.
Following query for searching "ID" is working fine:
conn = new MySqlConnection(cs);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "select * from catalog_product_entity where entity_id = ?Id";
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
cmd.Parameters.Add("?Id", SqlDbType.Text).Value = ProductList[i].ProductId.ToString();
adp.Fill(MagentoProduct);
Now, I want to search exact string value in table. I am using following code and its giving empty result:
My Code:
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand("select * from catalog_category_entity_varchar where value = #Value;", conn);
cmd.Parameters.AddWithValue("#Value", "Storybooks");
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
log.WriteEntry(r.GetString("value"));
}
This is the problem:
where value = '?cname'
That's specifying ?cname as the literal value you're searching for - when you actually just want the parameter. Remove the quotes and it should be fine:
where value = ?cname
(You should use using statements for the connection and command, mind you...)
You could try SQL Reader
c = new MySqlCommand("select * from catalog_product_entity where column_nam = #Value;", conn);
c.Parameters.AddWithValue("#Value", your string);
MySqlDataReader r = c.ExecuteReader();
and then use Reader methods like reader.GetString("column_name"), ....
I am facing a little problem in my code to add data to sql database attached with my program in ASP.net/C#. Here's code:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
SqlConnection cnn = new SqlConnection(ConnectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Id from TableName";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " TableName ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["TableName"].NewRow();
drow["Id"] = TextBox1.Text;
ds.Tables["TableName "].Rows.Add(drow);
da.Update(ds, " TableName ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
Even when I entered any integer value to the text box, it shows an error message that object is not set to an instance on code:
DataRow drow = ds.Tables["TableName"].NewRow();
Please guide.
Thanks.
This seems like a very bad way of inserting data. Have you looked at the Entity Framework or Linq2Sql? Alternatively you could just use a standard SqlCommand and set the CommandText yourself.
Any of these would provide a cleaner solution.
Eg: With ADO.NET (Connecting to SQLite):
var conn = new SQLiteConnection(string.Format(Constants.SQLiteConnectionString, "db.db3"));
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction()) {
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "INSERT INTO TableName (Id) VALUES (#Id)";
cmd.Parameters.AddWithValue("#Id", someTextVariable);
cmd.ExecuteNonQuery();
}
}