comboBox without duplicated values - Visual Studio 2013 C++ and MySql - mysql

I have a 0 error program that consists in a visual studio windows form c++ connected to mysql. everything works fine!
The thing is: i have a comboBox that gets the info from the column i want, but that column is not a primary key, so it has duplicated or more values.
How can i show only one value of each in the comboBox?
Ty all !
COMBOBOX CODE:
private: void Fillcombo(void) {
String^ constring = L"datasource=127.0.0.1;port=3306;username=root;password=12345";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
MySqlCommand^ cmdDataBase = gcnew MySqlCommand("select * from batcel.maq_corte;", conDataBase);
MySqlDataReader^ myReader;
try{
conDataBase->Open();
myReader = cmdDataBase->ExecuteReader();
while (myReader->Read()){
String^vResponsavel;
vResponsavel = myReader->GetString("id_responsavel");
comboBox2->Items->Add(vResponsavel);

Or you can modify SQL request:
select * from batcel.maq_corte group by id_responsavel

I'm not quite familiar with the c++ cli syntax but I can give you the solution here.
You can use a list container to store the values from the column. But before inserting a value find whether the value exists in the list. If not insert the value and display it in the combobox.
e.g..
//This is just a pseudo code
list(string) somelist;
while (read){
String value;
value= read->GetString("id_responsavel");
if(! somelist.find(value)
{
somelist.insert(value);
combobox.add(value);
}

Related

Error when using textbox values inside string sql

"Select item from table1 where Spare parts='"+ textbox1.text+"'".
I have tried to replace item with Textbox2.text.
I used :
"Select'"& textbox2.text& "' from table1 where Spare parts='"+ textbox1.text+"'"
I got error.
I used "+ textbox2.text+" I got error too
What you have here is one of the fastest ways out there to get your app hacked. It is NOT how you include user input in an SQL statement.
To explain the right way, I also need to include the connection and command objects for context, so I may also have a different pattern for how I handle these than you're use to. I'm also assuming the mysql tag in the question is accurate (though I have my doubts), such that the correct code looks more like this:
string SQL = "Select item from table1 where `Spare parts`= #SpareParts";
using cn = new MySqlConnection("connection string here")
using cmd = new MySqlCommand(SQL, cn)
{
cmd.Parameters.AddWithValue("#SpareParts", TextBox1.Text);
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// ...
}
}
}
Note the backticks around Spare Parts, so it will be correctly treated as a single object name by MySql.

How to execute multiple statement with variables in C# OdbcCommand object

I want to execute below MySql queries at a time through OdbcCommand object within C# as dynamic query, it always fails:
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
set #row=0;
select * from
(
select #row:=#row+1 as my____row_num,
cities.`cityid`,
cities.`cityname`,
cities.`countryid`,
cities.`countryname` , '1' as my____data_row_created , '1' as
my____data_row_updated from `cities` ) p
where my____row_num>=101 and my____row_num<=200;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
I'm using below method to execute above MySql queries:
ExcuteCommand(Sql)
{
DataTable dt = new DataTable();
OdbcCommand SQLCommand = new OdbcCommand(Sql);
OdbcConnection Con = new OdbcConnection(ConnectionString);
try
{
Con.Open();
SQLCommand.Connection = Con;
OdbcDataAdapter da = new OdbcDataAdapter(SQLCommand);
da.Fill(dt);
Con.Close();
Con.Dispose();
}
catch
{
try
{
Con.Close();
}
catch { }
throw;
}
return dt;
}
I found solution from here. While executing multiple dynamic MySql statements through ODBC in C# we have two options:
Execute separately every command
Use stored procedures
In my case I'm bound to use dynamic-quires because I'm having only read-access on database.
Solution:
Rather than Declaring variable and set it, I used another technique to use a session variable as a derived table and crossed join it with the main table. See the following query, in my scenario I changes to below MySql query code and removed both SET SESSION related code from the query, and it worked properly:
select * from
(
select #row:=#row+1 as my____row_num,
cities.`cityid`,
cities.`cityname`,
cities.`countryid`,
cities.`countryname` , '1' as my____data_row_created , '1' as
my____data_row_updated from `cities` ,(select #row:=0) as t ) p
where my____row_num>=101 and my____row_num<=200;
I'm not going to attempt to solve your MySQL problem, but your C# code can and should be written better, and since comments are not suited for codes, I thought I'd better write this as an answer.
So here is an improvement to your C# part:
DataTable FillDataTable(string sql)
{
var dataTable = new DataTable();
using(var con = new OdbcConnection(ConnectionString))
{
using(var command = new OdbcCommand(sql, con))
{
using(var dataAdapter = new OdbcDataAdapter(SQLCommand))
{
dataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
Points of interests:
I've renamed your method to a more descriptive name. ExecuteCommand doesn't say anything about what this method does. FillDataTable is self explanatory.
The using statement ensures the disposing of instances implementing the IDisposable interface - And almost all ADO.Net classes are implementing it.
The disposing of an OdbcConnection also close it, so you don't need to explicitly close it yourself.
There is no point of catching exceptions if you are not doing anything with them. The thumb rule is to throw early, catch late. (actually catch as soon as you can do something about it like write to log, show a message to the user, retry etc').
DataAdapters implicitly opens the Connection object, no need to explicitly open it.
Other two improvements you can do are:
Have this method also accepts parameters.
Have this method also accept the CommandType as a parameter (currently, using a stored procedure with this will not work since the default value of CommandType is Text
So, an even better version would be this:
DataTable FillDataTable(string sql, CommandType commandType, params OdbcParameter[] parameters)
{
var dataTable = new DataTable();
using(var con = new OdbcConnection(ConnectionString))
{
using(var command = new OdbcCommand(sql, con))
{
command.CommandType = commandType;
command.Parameters.AddRange(parameters);
using(var dataAdapter = new OdbcDataAdapter(SQLCommand))
{
dataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
If you want to improve that even further, You can have a look at my GitHub ADONETHelper project - There I have a single private method for Execute, and the methods for filling data tables, filling data sets, execute non query etc' all use this single method.
would you please try this instead
declare #row int
set #row=0;
select * from
(
select SUM(#row,1) as my____row_num,
cities.cityid as CityID,
cities.cityname as CityName,
cities.countryid as CountryID,
cities.countryname as CountryName ,
'1' as my____data_row_created , '1' as my____data_row_updated from cities) //i did not understand the meaning of this
where (my____row_num BETWEEN 100 AND 200 )
backEnd
ExcuteCommand(Sql)
{
<AddThis>ConnectionString= ConfigurationManager.ConnectionStrings["YourDataBaseLocation_OR_theConnectionCreatedViaProperties"].Connectionstring;</AddThis>
DataTable dt = new DataTable();
<deleteThis> OdbcCommand SQLCommand = new OdbcCommand(Sql);</deletethis>
//You Need to add the connection you have used it and Odbc
//Command.CommandType= CommandType.StoredProcedure();
OdbcConnection Con = new OdbcConnection(ConnectionString);
<AddThis>OdbcCommand SqlCommand = new OdbcCommand(Sql,Con);</AddThis>
try
{
Con.Open();
SQLCommand.Connection = Con;
OdbcDataAdapter da = new OdbcDataAdapter(SQLCommand);
da.Fill(dt);
<add this > SQLCommand.ExecuteNonQuery();</Add this>
Con.Close();
<delete> Con.Dispose();</delete>
}
catch
{
try
{
Con.Close();
}
catch (Exception e) { }
throw (e);
}
return dt;
}

MySQL query using float variables

I'm working on a small project (my first MySQL one) and I got to a point where I'm coding a query to insert data in a table.
These are my variables:
float min=0, max=0, med=0, aux;
string data, stringTipo, stringPapel, stringCompanhia;
I converted the std::strings to System::strings using:
String^ sCom = gcnew String(stringCompanhia.c_str());
String^ sTipo = gcnew String(stringTipo.c_str());
String^ sPap = gcnew String(stringPapel.c_str());
String^ sDat = gcnew String(data.c_str());
This is my query:
MySqlCommand^ cmdDataBase=gcnew MySqlCommand("insert into bdi.acoes (companhia,papel,tipo,min,max,med,data) values('"+sCom+"','"+sPap,+"','"+sTipo+"','"+min+"','"+max+"','"+med+"','"+sDat+"');",conDataBase);
As of now, I'm working on a query to insert data, stringTipo, stringPapel, stringCompanhia, min, max and med into my acoes table.
For now I got errors related to the floats only, I do BELIEVE that my string conversion is rather fine for inserting data into my query, but any suggestions are welcome.
These are the errors I'm getting (note: all of them are the same for all floats).
error C2678: binary '+' : no operator found which takes a left-hand operand of type 'const char [4]' (or there is no acceptable conversion)

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

How to compare textbox value with the sql database value in c#?

How to compare textbox value with the sql database value in c#?
im a beginner n i have to make a project. i only know how to connect sql database with the c# project.
and also tell me any tutorial, link or anything that can help me.
Here is a code sample that will assist you with this. Of course you can embelish on this as much as necessary but it will provide you the basics -- given the data that I have from your question.
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Please enter a value into the text box.");
this.textBox1.Focus();
return;
}
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
connectionStringBuilder.DataSource = ".";
connectionStringBuilder.InitialCatalog = "TEMP";
connectionStringBuilder.IntegratedSecurity = true;
SqlConnection connection = new SqlConnection(connectionStringBuilder.ToString());
SqlCommand command = new SqlCommand("SELECT Column1 FROM TableA WHERE PKColumn = 1", connection);
connection.Open();
string value = command.ExecuteScalar() as string;
connection.Close();
if (textBox1.Text.Equals(value))
{
MessageBox.Show("The values are equal!");
}
else
{
MessageBox.Show("The values are not equal!");
}
If you have some other specifics regarding this question I can probably give you a more specific example.