Working with MySQL in C# - c#

Here's my code to print the data to the terminal:
public static void WriteData()
{
string connString = "SERVER=localhost;" +
"DATABASE=db;" +
"UID=user;" +
"PASSWORD=pass;";
MySqlConnection connection = new MySqlConnection(connString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT * FROM table1";
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
Console.Write(reader.GetValue(i).ToString() + " ");
Console.WriteLine();
}
connection.Close();
}
Now I'd like to view the results in a DataGridView. All the tutorials I've found involve adding external data sources to the grid, which I have no idea how to do in MySQL. (Also please note that I have no experience in developing Windows Forms, but I guess that most GUI development is drag-and-drop anyway).

As Daniel Said, a DataTable would be sufficient for this.
If you use a DataAdapter you can fill a DataTable and then bind this to your grid, e.g.:
DataGridView.DataSource = DataTable
If you set the DataGridView to auto generate columns then you will see each column in the data table, else, you need to specify each column.
Here is the code to populate a data table from a SQL command:
using (SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter(oSqlCommand))
{
DataTable oDataTable = new DataTable();
oSqlDataAdapter.Fill(oDataTable);
return oDataTable;
}
Obviously you would use MySQL classes instead of SQL classes.

the best way to learn about this is to learn about data tables and datasets. This is pretty much the same across the board. You can do it drag and drop in visual studio but it is best to have more control over it.
this is an excellent tutorial in 4 parts
http://www.codeproject.com/KB/grid/practicalguidedatagrids1.aspx

If I'm not wrong, the mysql connector for .net has MySqlAdapter class that you can use to get a DataSet and then put the information into a Datatable or a Grid in the way WraithNath 've said.

Related

Best way to import data from DataGridView into Oracle 11g

Hello everyone since I'm new to C# would like to ask you if there are better ways to import data from DataGridView into Oracle 11g. Best with an example. Here is my current code and I use parameters. Because of my drivers I can't use AddWithValue. Thank you
private void Btn_SAVE_IN_DATABASE_VEUPEN_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView2.Rows.Count - 1; i++) //Schleife für INSERT Befehl
{
OracleConnection con = new OracleConnection("Data Source=(***********************");
con.Open();
string sql = "INSERT INTO AFTERSALES.INPUT_BOARDLEVEL_REPAIR_VEUPEN (BLR_REPORT_DATE, MONTH_OF_REPAIR_END, PCB_COUNTER, MANUFACTURER, REPORTING_OUTBOUND_DATE, EMPTY, QTY)"
+ "VALUES (:BLR_REPORT_DATE, :MONTH_OF_REPAIR_END, :PCB_COUNTER, :MANUFACTURER, :REPORTING_OUTBOUND_DATE, :EMPTY, :QTY)";
OracleCommand cmd = new OracleCommand(sql, con);
cmd.Parameters.Add(":BLR_REPORT_DATE", Convert.ToDateTime(dataGridView2.Rows[i].Cells[0].Value).ToString("dd.MM.yyyy"));
cmd.Parameters.Add(":MONTH_OF_REPAIR_END", dataGridView2.Rows[i].Cells[1].Value);
cmd.Parameters.Add(":PCB_COUNTER", dataGridView2.Rows[i].Cells[2].Value);
cmd.Parameters.Add(":MANUFACTURER", dataGridView2.Rows[i].Cells[3].Value);
cmd.Parameters.Add(":REPORTING_OUTBOUND_DATE", Convert.ToDateTime(dataGridView2.Rows[i].Cells[4].Value).ToString("dd.MM.yyyy"));
cmd.Parameters.Add(":EMPTY", dataGridView2.Rows[i].Cells[5].Value);
cmd.Parameters.Add(":QTY", dataGridView2.Rows[i].Cells[6].Value);
cmd.ExecuteNonQuery();
con.Close();
}
}
my two cents:
1 - why would you read from the grid? have one of your collegues add a single new column in between the existing columns and your code will create garbage. read the values from underlying datasource
2 - why do you recreate the connection for every row? Create it once, open it once, insert
x-rows, close it once
3 - i'd likely perform the entire operation with a transaction

Insert database data into listbox C#

Disclaimer: I have no prior experience with querying databases from c# code (so go easy on me)
I am trying to insert data from my SQL Server database into my listbox. Right now I am trying this in the form of an array. I first connect to the database, and then insert the "state" from the database into the index of the array. I want all 50 states to be put into my array and then this information to be put into my listbox. Right now, my data is being inserted but when I view it in the list box it shows System.Data.SqlClient.SqlCommand.
public string connString = "Not displaying this for security reasons, it is set up correctly though."; //Setting up the connection to my DB
public frmState()
{
InitializeComponent();
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmState_FormClosed);
using (SqlConnection dbConn = new SqlConnection(connString))
{
dbConn.Open();
string cmdString = "select State_Name from [State]";
SqlCommand cmd = new SqlCommand(cmdString, dbConn);
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
string[] stateList = new string[50];
for (int i = 1; i <= 50; i++)
{
stateList[i - 1] = cmd.ToString();
}
for (int i = 0; i < stateList.Length; i++)
{
lbStates.Items.Add(stateList[i].ToString());
}
}
}
finally
{
reader.Close();
}
}
}
Also, I am aware that as of right now I will be showing the same state 50 times. I am trying to figure out how to insert one state at a time. Is this an efficient way of doing this? Also, any tips on working with databases in c#? I am on Visual Studio 2017 and Microsoft SQL Server 2016.
The problem comes from where you did:
stateList[i - 1] = cmd.ToString();
It's wrong because you are converting an SqlCommand object to string and putting it inside an array of type of string to retrieve data from your SqlCommand.
Changing the above line as below will fix your problem:
tateList[i - 1] = reader.GetString(0);
any tips on working with databases in c#?
for a beginner with C# and SQL, I suggest you to keep learning basic database access tools of ADO.net like using SqlDataReader, SqlDataReader, SqlDataAdapter, ... . but to have professional and of course secure application witch also needs to be simple; you have to move toward using ORM tool (witch are medium to access database securely) like "Entity Framework", linq, ... witch will make talking to database much more convenient.
Complementary:
I suggest you to reading this tutorial about how to use SqlDataReader.

C# write datagridview data into a SQL Server table

I have a four column table in a SQL Server database. The info for the first three columns is supplied by another source. Column 4 is set to null by default.
I then have a win form with a datatable that populates with the information from the SQL Server database using the following code:
public DataTable populateFormList()
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.sqlConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM of_formlist_raw", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
datagridview2.DataSource = populateFormList();
datagridview2.Refresh();
Now that works fine in obtaining my data.
The user can then make changes to the null values in column 4.
How can I easily write these changes from the datatable back into the SQL Server table?
In other words, once the on screen datatable has additional values, how can I then store the updated information back in the SQL Server database from which it was originally obtained from?
Thanks.
Try something like this and just pass (DataTable)datagridview2.DataSource as the data table:
private static void BulkInsertToSQL(DataTable dt, string tableName)
{
using (SqlConnection con = new SqlConnection(_DB))
{
SqlBulkCopy sbc = new SqlBulkCopy(con);
sbc.DestinationTableName = tableName;
//if your DB col names don’t match your data table column names 100%
//then relate the source data table column names with the destination DB cols
sbc.ColumnMappings.Add("DBAttributeName1", "DTColumnName1");
sbc.ColumnMappings.Add("DBAttributeName2", "DTColumnName2");
sbc.ColumnMappings.Add("DBAttributeName3", "DTColumnName3");
sbc.ColumnMappings.Add("DBAttributeName4", "DTColumnName4");
con.Open();
sbc.WriteToServer(dt);
con.Close();
}
}
2 options, with or without TableAdapter.
I would recommend to read this in MSDN for TableAdapter
They're using BindingSources too, which are excellent components, easy-to-use.
Without TableAdapter, read this, the "Update Records Using Command Objects" part.

Problem with ADO.NET UPDATE code

Could somebody take a quick peek at my ado.net code? I am trying to update the row from a dataset, but it just isn't working. I am missing some elemental piece of the code, and it is just eluding me. I have verified that the DataRow actually has the correct data in it, so the row itself is accurate.
Many thanks in advance.
try
{
//basic ado.net objects
SqlDataAdapter dbAdapter = null;
DataSet returnDS2 = new DataSet();
//a new sql connection
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Server=myserver.mydomain.com;"
+ "Database=mydatabase;"
+ "User ID=myuserid;"
+ "Password=mypassword;"
+ "Trusted_Connection=True;";
//the sqlQuery
string sqlQuery = "select * from AVLUpdateMessages WHERE ID = 21";
//another ado.net object for the command
SqlCommand cmd = new SqlCommand();
cmd.Connection = myConn;
cmd.CommandText = sqlQuery;
//open the connection, execute the SQL statement and then close the connection.
myConn.Open();
//instantiate and fill the sqldataadapter
dbAdapter = new SqlDataAdapter(cmd);
dbAdapter.Fill(returnDS2, #"AVLUpdateMessages");
//loop through all of the rows; I have verified that the rows are correct and returns the correct data from the db
for (int i = 0; i <= returnDS2.Tables[0].Rows.Count - 1; i++)
{
DataRow row = returnDS2.Tables[0].Rows[i];
row.BeginEdit();
row["UpdatedText"] = #"This is a test...";
row.EndEdit();
}
//let's accept the changes
dbAdapter.Update(returnDS2, "AVLUpdateMessages");
returnDS2.AcceptChanges();
myConn.Close();
}
I think you need an update query in your data adapter. I know, this sucks... Alternatively you can use CommandBuilder class to automatically generate queries for CRUD operations.
example at: http://www.programmersheaven.com/2/FAQ-ADONET-CommandBuilder-Prepare-Dataset
You might be able to use SqlCommandBuilder to help out. After the Fill call, add the following statement. That will associate a command builder with the data adapter and (if there is a primary key available) it should generate the update statement for you. Note that there is some expense behind the command builder. It may not be much relative to everything else, but it does involve looking at schema information (to get primary key information, field names, field types, etc.) for the table and generating INSERT, DELETE, and UPDATE statements involving all fields in the table.
SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter);
Wait, why not something like
update AVLUpdateMessages set UpdatedText = 'This is a test...' where id = 21
If you're picking through all the rows of a table to update one at a time, you're probably doing it wrong. SQL is your friend.

C# change mdb filed data type to memo and save it

I would like to change the data type in my db from "Text" to "Memo".
first of all, I didnt find the "Memo" data type in c#.
second: I got the following code to execute command in the db:
public void SQLCommand(String strSQL)
{
OleDbConnection objConnection = null;
OleDbCommand objCmd = null;
String strConnection;
strConnection = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "\\tasks.mdb";
objConnection = new OleDbConnection(strConnection);
objConnection.ConnectionString = strConnection;
objConnection.Open();
objCmd = new OleDbCommand(strSQL, objConnection);
objCmd.ExecuteNonQuery();
objConnection.Close();
UpdateListView();
}
how can I change the 3rd column's data type and save it?
I can change the data type when form_load with this function:
public void tst()
{
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * from Tasks", conn);
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
dt.Columns[3].DataType = System.Type.GetType("System.String");
conn.Close();
}
but with this function, it change to the data type to string > and I want memo.
also this function is no good since I need to run it everytime and if I change it permanently to memo I will just have to make a little if at the begining.
~Thanks.
String in C# is the equivalent of both Text and Memo in that it supports texts of either length.
If I understand the question correctly I think you're misunderstanding what you're actually doing in your code. When you set the DataType of the column, you're not changing the database in any way, you are just changing the datatype of a column in the DataTable instance that you've created.
If you actually want to change the structure of the database the best way would probably be to do it manually in Access, since I'm not sure if that's really supported in ADO.Net (I suppose you might be able to do it using ALTER statements). Otherwise you might be able to do it using DAO which used to be the Access/Jet way of doing things like that, but that was deprecated quite a while ago so might not work well in .Net.

Categories