How to get all table names ans schemas without loop - c#

I have to retrieve the names and the schemas of old tables for creating the new tables in new database within a program. I wrote this procedure which is working. In first part I get the names of tables and store it in MyArray and the in second part I put this names in query string. But in the second part I get in first read the name of table and the following data is the schema.
Is there a solution like this:(this is not working I tried :)
MySqlCommand cmd = new MySqlCommand("SHOW * CREATE TABLE " + DbName, conn);
My function is there:
private int CopySchemas(string pathname)
{
string [] MyArray = new string[11];
int index = 0;
using (MySqlConnection conn = new MySqlConnection(connstr))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + DbName+"'",conn))
{
conn.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyArray[index] = reader.GetValue(0).ToString();
++index;
}
reader.Dispose();
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
for (int i = 0; i < MyArray.Length; ++i)
{
string tblname = MyArray[i];
string fname = pathname +"\\" + tblname + ".sql";
MySqlCommand cmd = new MySqlCommand("SHOW CREATE TABLE " + DbName + "." + tblname, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string fname = pathname +"\\" + reader.GetValues(0) + ".sql";
string schema = reader.GetValue(1).ToString();
File.WriteAllText(fname,schema);
}
reader.Dispose();
}
}
return index;
}

Finally I sawed that for each connection must have only one reader.
So I opened two connections and for each connection I associated a reader. So I don't use an array for storing the tables names I use only the second reader where I get the tables names and schemas.
Here is the code:
private int CopySchemas(string pathname)
{
int index = 0;
MySqlConnection conn1 = new MySqlConnection(PublicVariables.cs);
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + PublicVariables.DbName + "'", conn))
{
conn.Open();
conn1.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string tblname = reader.GetValue(0).ToString();
MySqlCommand cmd1 = new MySqlCommand("SHOW CREATE TABLE " + PublicVariables.DbName + "." + tblname, conn1);
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string fname = pathname + "\\" + reader1.GetValue(0).ToString() + ".sql";
string schema = reader1.GetValue(1).ToString();
File.WriteAllText(fname, schema);
}
reader1.Dispose();
++index;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
}
return index;
}

Related

i get the error MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax

MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}

update selected data in mysql in c#

how to update selected data in mysql in c#?
this is my code when i press button2 . all data "jumlah_product" minus two.
i want to make just minus two "jumlah_product" in selected data.
private void button2_Click_1(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost;Database=maindata;Uid=root;pwd=firmandoang;";
string Query = "select * from maindata.product_database where idproduct = '" + this.textBox1.Text + "' OR namaproduct LIKE '" + this.textBox1.Text + "'";
MySqlConnection conn = new MySqlConnection(MyConnectionString);
MySqlCommand command = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
myReader = command.ExecuteReader();
try
{
if (myReader.Read())
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[1].Value = myReader.GetString("namaproduct");
row.Cells[2].Value = myReader.GetString("hargaproduct");
int count = Convert.ToInt32(textBox2.Text);
int price = Convert.ToInt32(row.Cells[2].Value);
row.Cells[3].Value = count;
row.Cells[4].Value = price *= count;
dataGridView1.Rows.Add(row);
string update = "UPDATE maindata.product_database SET jumlah_product=(jumlah_product - '" + count + "')";
MySqlCommand cmd = new MySqlCommand(update, conn);
MySqlDataReader reader;
myReader.Close();
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
}
else
{
MessageBox.Show("No Data ");
}
sorry for bad english . I hope you understand :)

how to save datagridview bulk data to sql database while the datagridview data binded with images to SQL database in c#

There are many questions similar to my issue,but none of them helped away from this issue..
I'm working with win-forms, coding in C#, using SQL server
I have a datagridview which is retrieving data from database with some data as text and some are images.
My code is as given below to save the datagridview data to database
but this is not working and throwing an error an object or column name is missing or empty. for select into statements verify ..........
Please solve my issue..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO dailydemo VALUES ("
+ dataGridView1.Rows[i].Cells["S_No"].Value + ", "
+ dataGridView1.Rows[i].Cells["Employee_Id"].Value + ", "
+ dataGridView1.Rows[i].Cells["Employee_Name"].Value + ", "
+ dataGridView1.Rows[i].Cells["In_time"].Value + ", "
+ dataGridView1.Rows[i].Cells["Out_Time"].Value + ", "
+ dataGridView1.Rows[i].Cells["Date"].Value + ", "
+ dataGridView1.Rows[i].Cells["Week_No_of_The_Month"].Value + ", "
+ dataGridView1.Rows[i].Cells["Attendance"].Value + ", "
+ dataGridView1.Rows[i].Cells["Work_status"].Value + ", "
+ dataGridView1.Rows[i].Cells["Remarks"].Value + ", "
+ dataGridView1.Rows[i].Cells["Image_of_Employee"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
Use this may be Help full...
byte[] imgByteArrLogo = new byte[0];
using (SqlConnection con = new SqlConnection("Your Connection string Here"))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
using (SqlTransaction _pTrans = con.BeginTransaction(IsolationLevel.ReadCommitted))
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells["Image_of_Employee"].Value != null)
{
Image _dgvImage = (Image)dataGridView1.Rows[i].Cells["Image_of_Employee"].Value;
MemoryStream ms = new MemoryStream();
_dgvImage.Save(ms, ImageFormat.Jpeg);
imgByteArrLogo = new byte[ms.Length];
ms.Position = 0;
ms.Read(imgByteArrLogo, 0, imgByteArrLogo.Length);
}
else
{
imgByteArrLogo = new byte[0];
}
try
{
string sql = "INSERT INTO dailydemo (S_No,Employee_Id ,Employee_Name ,In_time ,Out_Time ,Date,Week_No_of_The_Month,Attendance,Work_status,Remarks,Image_of_Employee) VALUES (#S_No,#Employee_Id ,#Employee_Name ,#In_time ,#Out_Time ,#Date,#Week_No_of_The_Month,#Attendance,#Work_status,#Remarks,#Image_of_Employee)";
using (SqlCommand cmd = new SqlCommand(sql, con, _pTrans))
{
cmd.Parameters.Add(new SqlParameter("#S_No", dataGridView1.Rows[i].Cells["S_No"].Value));
cmd.Parameters.Add(new SqlParameter("#Employee_Id", dataGridView1.Rows[i].Cells["Employee_Id"].Value));
cmd.Parameters.Add(new SqlParameter("#Employee_Name", dataGridView1.Rows[i].Cells["Employee_Name"].Value));
cmd.Parameters.Add(new SqlParameter("#In_time", dataGridView1.Rows[i].Cells["In_time"].Value));
cmd.Parameters.Add(new SqlParameter("#Out_Time", dataGridView1.Rows[i].Cells["Out_Time"].Value));
cmd.Parameters.Add(new SqlParameter("#Week_No_of_The_Month", dataGridView1.Rows[i].Cells["Week_No_of_The_Month"].Value));
cmd.Parameters.Add(new SqlParameter("#Attendance", dataGridView1.Rows[i].Cells["Attendance"].Value));
cmd.Parameters.Add(new SqlParameter("#Work_status", dataGridView1.Rows[i].Cells["Work_status"].Value));
cmd.Parameters.Add(new SqlParameter("#Remarks", dataGridView1.Rows[i].Cells["Remarks"].Value));
cmd.Parameters.Add(new SqlParameter("#Image_of_Employee", imgByteArrLogo));
cmd.ExecuteScalar();
}
}
catch (Exception exp)
{
_pTrans.Rollback();
con.Close();
_pTrans.Dispose();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
_pTrans.Commit();
_pTrans.Dispose();
con.Close();
}
}
UPDATE :
Please note that in this example I used your datagridview cell name as sql table column names, if column names are diffrent then modify it.

Getting unknown data from SQL Server using SqlDataReader

I use this code for getting data from SQL Server:
string rootname = "[" + nameroot + "]";
string retVal = "";
string constring = "Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;";
SqlConnection conobj = new SqlConnection(constring);
string commandtext = "select distinct " + rootname + " from TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
//retVal = dr[nameroot].ToString();
}
conobj.Close();
Now I need this data inserted into a variable or textbox.
The problem is that my values are unknown
Solution 1 :
You can use Index value.
Try This:
while (dr.Read())
{
retVal = dr[0].ToString();
}
Solution 2 :
You can also use alias name.
string commandtext = "select distinct " + rootname + " as myrootname from
TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
retVal = dr["myrootname"].ToString();
}
Suggestion: Your Query is open to SQL Injection Attacks i would suggest you to use Parameterised Queries to avoid them.
Solution 3: Using Parameterised Queries
if you want to add all rootname values you need to add all values to List.
List<string> list = new List<string>();
string commandtext = "select distinct "+rootname+" as myrootname from
TBLJobsRootName where MenuId between 1 and #countroot";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
comobj.Parameters.AddWithValue("#countroot",countroot);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
lis.Add(dr["myrootname"].ToString());
}
//You can retunrn list

How can I export GridView to MS Access in C#

I want to export grid to MS Access in C#
Here's the code that I've tried:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
SqlDataAdapter adapter1 = new SqlDataAdapter();
adapter1.Fill(dtFillGrid);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
foreach (DataTable table in dtFillGrid.Rows) {
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns) {
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows) {
foreach (DataRow row in table.Rows) {
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray) {
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText; command.ExecuteNonQuery();
}
}
accessConnection.Close();
How can I do this?
I would suggest you create the MDB database, create the table(s) you want using sql, then at runtime bind the gridview, or loop through the results and do a batch import.
See here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms677200(v=vs.85).aspx
using ADOX; // add a COM reference to "Microsoft ADO Ext. x.x for DDL and Security"
static void CreateMdb(string fileNameWithPath)
{
ADOX.Catalog cat = new ADOX.Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
if you dont have problem with payement you can use 'Spire doc' to save datagrid into msAccess like so :
private void btnExportToAccess_Click(object sender, EventArgs e)
{
Spire.DataExport.Access.AccessExport accessExport = new
Spire.DataExport.Access.AccessExport();
accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
accessExport.DatabaseName = #"..\..\ToMdb.mdb";
accessExport.TableName = "ExportFromDatatable";
accessExport.SaveToFile();
}
and Here a link where you can find more clarification
Here I am not export gridview in MS Access but I made a database in MS Access by using C# with the help of this code:
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
Yes I tell you to all of you that we don't need to export data by gridview to MS Access , we can do this directly create database in MS Access using C#

Categories

Resources