Executing a query i got Two different results PhpMyAdmin and C# - c#

Hello if i execute the following query in PhpMyAdmin i have 5 Result.
If i execute the exactly query into C# i get back only 1 Result.
I have been beating my head against the table for 2 days but I can't find the solution.
Some ideas?
SELECT
tbl_orders.Data_payment,
tbl_customers.City,
tbl_customers.Country,
tbl_orders.Price,
tbl_orders.state_order,
tbl_products.Product_ID,
tbl_products.Name
FROM
tbl_orders
INNER JOIN
tbl_customers ON tbl_orders.fk_customer_id = tbl_customers.Customer_ID
INNER JOIN
tbl_products ON tbl_orders.fk_product_id = tbl_products.Product_ID
WHERE
tbl_products.Product_ID = '2'
AND tbl_customers.Country = 'Russia'
AND tbl_orders.Data_payment BETWEEN '2019-04-01' AND '2020-04-01'
private void test_load(string query)
{ DataTable dt = new DataTable();
try
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
conn.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
dt.Load(dr);
MessageBox.Show(dt.Rows.Count.ToString());
dataGridView1.DataSource = dt;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("err test_load " + ex);
}
}

After adding the database and testing the code you provided, I find that I still
can not reproduce your problem. I can get the same result in sql-query and in c# code.
You can see the following picture.
I also tested it, I find it is different from your picture.

Ok so i finally solve the problem.
This pice of code in not working it return only one row and should return more than one.
private DataTable test2_load(string query)
{
DataTable dt = new DataTable();
try
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
conn.Open();
using (MySqlDataReader data_reader = cmd.ExecuteReader())
{
dt.Load(data_reader);
}
}
}
return dt;
}
catch (Exception ex)
{
MessageBox.Show("err test_load " + ex);
return null;
}
}
This is working. It return the right number of rows
private void test3_load(string query)
{
MySqlConnection mysqlCon = new
MySqlConnection(MyConString);
mysqlCon.Open();
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand(query, mysqlCon);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}

Related

SqlDataAdapter is not updating datatable in the database

I'm trying to update datatable in the database using a SqlDataAdapter. I don't see any errors and also it's not updating the database.
I tried other solutions in the stackoverflow but still no luck. Here is my code:
public void Update(DataTable dt, String tableName)
{
try
{
SqlDataAdapter da = new SqlDataAdapter();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
da.SelectCommand = new SqlCommand("SELECT * FROM " + tableName, connection);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.UpdateCommand = cmdBuilder.GetUpdateCommand(true);
da.AcceptChangesDuringUpdate = true;
int res = da.Update(dt);
}
}
catch (Exception oEx)
{
System.Diagnostics.Debug.WriteLine("Ex: " + oEx);
}
}
Thanks in advance for your help!

Gridview not binding and showing datas from my database

well, I've done everything on my behalf just to solve this problem. i'm trying to print the data from my database using grid view in asp.net using c# codes. can anyone tell me whats wrong and how to improve my codes. thank you.
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
You must fill the DataSet with data like this :
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TableName");
GridView1.DataSource = ds.Tables["TableName"];
GridView1.DataBind();
You're assigning an empty DataSet to your DataSource, without filling the results of your DataReader into the DataSet/DataTable.
using (MySqlConnection con = new MySqlConnection(""))
{
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
try
{
DataTable dt = new DataTable();
using (MySqlDataReader reader1 = cmd.ExecuteReader())
{
dt.Load(reader1);
}
GridView1.DataSource = dt ;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

Datagridview with query in C#

I have 2 tables in MySql (privacy , lawsuit_under_500) ,
In privacy i have 2 columns (id , nameofcase ) ,
In lawsuit_under_500 4 columns(id,nameofcase,priceone,pricetwo) ,
I make a form with a datagridview and i want to execute this query :
select privacy.id,lawsuit_under_500.id,privacy.nameofcase, lawsuit_under_500.priceone, lawsuit_under_500.pricetwo
From privacy inner join lawsuit_under_500
where lawsuit_under_500.id=5 and privacy.id=1 || lawsuit_under_500.id=1 and privacy.id=2 || lawsuit_under_500.id=10 and privacy.id=3
ORDER BY privacy.id
In the form i have:
public Form55()
{
InitializeComponent();
}
private void Form55_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have put the tables in my DataSet but I cant figure out how to make it. I tried to make privacyBindingSourse in the datagridview and i added manually 2 buttons for priceone and pricetwo put i cant put the query so i can get the information.
Any ideas/help how to make it ?
BEFORE YOU ANSWER IF YOU HAVE ANY QUESTION PLEASE ASK ME
using MySql.Data.MySqlClient;
MySqlConnection conn = new MySqlConnection("Your MY SQL connection");
MySqlCommand cmd = new MySqlCommand("Your Mysql query");
MySqlDataReader dr=cmd.ExecuteReader();
gridview1.datasource=dr;
gridview1.databind();
// try this also
connectionString = "Your Connection";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("Your Query", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
I made it with this way
private void Form56_Load(object sender, EventArgs e)
{
try
{
MySqlConnection cnn = new MySqlConnection("MY CONNECTION");
cnn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
static public SqlCeConnection OpenSQL()
{
SqlCeConnection cncount = new SqlCeConnection(#"Data Source = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Database.sdf; Password =''");
return cncount;
}
static public DataTable DoSelect( string strSQL)
{
SqlCeConnection cn = OpenSQL();
DataTable dtRetValue = new DataTable();
using (SqlCeDataAdapter da = new SqlCeDataAdapter())
{
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = strSQL;
da.SelectCommand = cmd;
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
try
{
//using (SqlCeDataReader reader = da.SelectCommand.ExecuteReader())
SqlCeDataReader metsDr = da.SelectCommand.ExecuteReader();
dtRetValue.Load(metsDr);
return dtRetValue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error - DoSelect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
}
}
}
}
Insert in Button
string sql1 = "YOURE QUERY ";
DataTable dt1 = SQLcode.DoSelect(sql1);
dgvcompany.DataSource = dt1;

Oracle database table in gridview

I want to get the result from a query in my oracle database and put it in a gridview. Now my problem is, I have no idea how to output it in the gridview. I am using the gridview from the toolbox and my oracle connection is working. I also have the right SELECT query and I can output that in a listbox. I just have no idea how to do this in a gridview. I looked for it and I came across this: How to populate gridview with mysql? Although this doesn't help me.
How can I output it in a gridview so that it looks exactly the same as a normal table in the oracle database?
What should I use and how?
This is my code:
public void read()
{
try
{
var conn = new OracleConnection("")
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To bind a DataTable to a DataGridView your code need simply to be changed to
public void read()
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The OracleDataReader could be passed to the Load method of the DataTable and then the table is ready to be bound to the DataGridView DataSource property. I have also added some using statement to ensure proper disposing of the disposable objects employed. (In particular the OracleConnection is very expensive to not close in case of exceptions)
You can use DataSet too:
public void read()
{
try
{
OracleConnection conn = new OracleConnection("");
OracleCommand cmd = new OracleCommand("select * from t1", conn);
conn.Open();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
First establish connection in case, you didnt establish globally by using connection string. Then use oleDbcommand for the oracle sql command you want to execute. In my case, it is 'select * from table_name' which would show all data from table to datagrid. I wrote this code in a button to display data on data grid.
{
OleDbConnection conn = new OleDbConnection("");
OleDbCommand cmd = new OleDbCommand("select * from table_name", conn);
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
conn.Close();
}
}

Categories

Resources