I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------
Related
Hi I have a script task which pick up the excel files from a folder. The files have several sheets with names 'Question 1', 'Question 2'....etc.
My problem is that it is not reading or accessing the above sheet with 'space' in between Question and 1...
but when i replace it with (_) i.e. Question_1, Question_2...it is getting retrieved..my script task code is as below..any suggestions what should i change in my code to pick the sheetname as original.
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Data.OleDb;
using System.Data.SqlClient;
//using System.Text.RegularExpressions;
namespace ST_0762ccf78a5c4709b806530e3c885949
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
// public static string RemoveSpecialCharacters(string str) { return str.Replace("[^A-Za-z0-9_\\\\.]")};
public void Main()
{
String FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
string StartingColumn = Dts.Variables["User::StartingColumn"].Value.ToString();
string EndingColumn = Dts.Variables["User::EndingColumn"].Value.ToString();
string StartReadingFromRow = Dts.Variables["User::StartReadingFromRow"].Value.ToString();
var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();
//Declare and initilize variables
string fileFullPath = "";
//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
string filename = "";
fileFullPath = FolderPath + "\\" + file.Name;
//filename = file.Name.Replace(".xlsx", "");
filename = file.Name.Replace("'", " ");
MessageBox.Show(fileFullPath);
//Create Excel Connection
string ConStr;
string HDR;
HDR = "YES";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1\"";
OleDbConnection cnn = new OleDbConnection(ConStr);
//Get the sheetname and filename as columns
/* SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["Pulse_All_Tables"].AcquireConnection(Dts.Transaction) as SqlConnection);
string SQLColumnList = "";
string SQLQueryToGetMatchingColumn = "";
SqlCommand cmd = myADONETConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLColumnList = (string)cmd.ExecuteScalar();*/
//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
//sheetname = sheetname.Replace(" ", string.Empty);
//string sheetname1 = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
//if (drSheet["TABLE_NAME"].ToString().Contains("$"))
if (!drSheet["Table_Name"].ToString().Contains("FilterDatabase") && !drSheet["Table_Name"].ToString().EndsWith("$'"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
//Display Sheet Name , you can comment it out
MessageBox.Show(sheetname);
//Load the DataTable with Sheet Data
//Get the sheetname and filename as columns
//OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + StartingColumn + StartReadingFromRow + ":" + EndingColumn + "]", cnn);
OleDbCommand oconn = new OleDbCommand("select " + "*" + ",'" + filename + "' AS FileName" + ",'" + sheetname + "' AS SheetName from [" + sheetname + StartingColumn + StartReadingFromRow + ":" + EndingColumn + "]", cnn);
//cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
//drop $from sheet name
sheetname = sheetname.Replace("$", "");
//sheetname = sheetname.Replace((sheetname.Replace("$", "")),"_");
//sheetname1 = sheetname.Replace(" ", "");
// Generate Create Table Script by using Header Column,It will drop the table if Exists and Recreate
string tableDDL = "";
tableDDL += "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = ";
tableDDL += "OBJECT_ID(N'[dbo].[" + filename + "_" + sheetname + "]') AND type in (N'U'))";
tableDDL += "Drop Table [dbo].[" + filename + "_" + sheetname + "]";
tableDDL += "Create table [" + filename + "_" + sheetname + "]";
tableDDL += "(";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)" + ",";
else
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)";
}
tableDDL += ")";
//use ADO.NET connection to Create Table from above Definition
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["Pulse_All_Tables"].AcquireConnection(Dts.Transaction) as SqlConnection);
//you can comment the messagebox, it is for debugging
MessageBox.Show(tableDDL.ToString());
SqlCommand myCommand = new SqlCommand(tableDDL, myADONETConnection);
myCommand.ExecuteNonQuery();
//Comment this message, it is for debugging
MessageBox.Show("TABLE IS CREATED");
//Load the data from DataTable to SQL Server Table.
SqlBulkCopy blk = new SqlBulkCopy(myADONETConnection);
blk.DestinationTableName = "[" + filename + "_" + sheetname + "]";
blk.WriteToServer(dt);
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
}
You will have to replace the ' in the Sheetname. Try building your query as in following example:
oconn = new OleDbCommand("SELECT * FROM " + ("[" + dr["TABLE_NAME"].ToString() + "B1:B1]").Replace("'", ""), cnn);
Following a short example app I used to test this logic with a dummy Excel file which featured 3 sheets:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.Data;
using Microsoft.Win32;
namespace ConsoleApp13
{
class Program
{
static void Main(string[] args)
{
string fileName = "c:\\temp\\test.xlsx";
string ConStr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=NO;Empty Text Mode=NullAsEmpty""", fileName);
OleDbConnection cnn = new OleDbConnection(ConStr);
cnn.Open();
DataTable dt = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in dt.Rows)
{
Console.WriteLine(dr["TABLE_NAME"]);
//currently hardcoded B1:B1 - has to be replaced with your StartColumn:EndColumn logic
string cmd = "SELECT * FROM " + ("[" + dr["TABLE_NAME"].ToString() + "B1:B1]").Replace("'", "");
Console.WriteLine("\t"+cmd);
DataTable dt2 = new DataTable();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd, cnn);
da.Fill(ds);
dt2 = ds.Tables[0];
foreach(DataRow dr2 in dt2.Rows)
{
Console.WriteLine("\t" + dr2[0].ToString());
}
}
cnn.Close();
Console.WriteLine("Ende...");
Console.ReadKey();
}
}
}
[WebMethod()]
public DataTable insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode,int pack,string error,string chk,string user,DateTime day,string ekb,string kbid)
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = null;
StringBuilder strSQL = new StringBuilder();
strConnString = "Server=localhost;UID=sa;PASSWORD=12345678;database=bds_pp_srct;Max Pool Size=400;Connect Timeout=600;";
strSQL.Append("INSERT INTO Hanheld (Part_Number,SRCT_Code,Dock_Code,Package,Error_Code,Chk_Type,LogUser,LogDate,ekb_order_no,Kanban_ID) VALUES ('" + partnumber + "','" + srctcode + "','" + dockcode + "','" + pack + "','" + error + "','" + chk + "','" + user + "','" + day + "','" + ekb + "','" + kbid + "') ");
//strSQL.Append(" WHERE [SRCT_Code] = '" + strCusID + "' ");
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL.ToString();
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds);
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
return dt;
}
This error :
System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
Try this one
private DataTable dataTable = new DataTable();
string connString = #"query string here";
string query = "select table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();
I think you are using DataSet in your code might be there would be a problem
so you first need to check where that DataSet contains datatable at 0 location
eg.
DataSet ds = new DataSet();
dtAdapter.Fill(ds);
if(ds != null && ds.Tables.Count > 0) {
//your logic
}
[WebMethod()]
public void insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode)
{
using (SqlConnection conn = new SqlConnection("Server=localhost;UID=sa;PASSWORD=12345678;database=Test;Max Pool Size=400;Connect Timeout=600;"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Hanheld(Part_Number,SRCT_Code,Dock_Code) VALUES(#partnumber,#srctcode,#dockcode)";
cmd.Parameters.AddWithValue("#partnumber", partnumber);
cmd.Parameters.AddWithValue("#srctcode", srctcode);
cmd.Parameters.AddWithValue("#dockcode", dockcode);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// MessgeBox.Show(e.Message.ToString(), "Error Message");
}
}
}
}
This my Be fixed
Can you please anyone tell me how to Excel all data with particular sheet names insert in MS-SQL table. I am using C# code with MVC 5, This is my code C# and MVC 5
string path1 = #"c:\users\vaio\documents\visual studio 2013\Projects\test\Test2\Content\";
string fileFullPath = Path.GetFullPath(path1);
excelConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + fileFullPath + ";Extended Properties=\"text;HDR=YES;FMT=Delimited\"";
}
DataSet data = new DataSet();
foreach (var sheetName in GetExcelSheetNames(excelConnectionString))
{
using (OleDbConnection con = new OleDbConnection(excelConnectionString))
{
var dataTable = new DataTable(sheetName);
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
using (TtestContext dc = new TtestContext())
{
for (int i = 0; i < dataTable.Tables[0].Rows.Count; i++)
{
string conn = ConfigurationManager.ConnectionStrings["TtestContext"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query2 = "Insert into ExcelTemps(Courier,F2,F3,F4,F5,F6,F7,F8,F9,F10) Values('"
+ dataTable.Tables[0].Rows[i][0].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][1].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][2].ToString().Replace("'", "''") + "' ,'"
+ dataTable.Tables[0].Rows[i][3].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][4].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][5].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][6].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][7].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][8].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][9].ToString().Replace("'", "''") + "','"
+ dataTable + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query2, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
return View();
}
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}
}
I have created this update function but I am gettng "SelectCommand.Connection property has not been initialized" error.Can anyone help me for this.My code is:
public void Update_Click(object sender, EventArgs e)
{
Button b = sender as Button;
b.ForeColor = Color.Blue;
b.Font.Bold = true;
string strTableName = Request.QueryString["table"];
DataTable dt = new DataTable();
DataTable dtColumn=new DataTable();
MySqlConnection sQLcONN = new MySqlConnection("connection");
sQLcONN.Open();
// MySqlCommand sqlcolum=new MySqlCommand("SELECT *FROM information_schema.columns WHERE table_name ="+strTableName);
// MySqlDataAdapter sqlDa1=new MySqlDataAdapter(sqlcolum);
// sqlDa1.Fill(dtColumn);
// MySqlCommand sqlCmd = new MySqlCommand("update " + strTableName + "set " + dtColumn.Rows[introws]["column_name"] + "='" + "txtTextbox" + dt.Rows[introws][0].ToString() + "' where " + dtColumn.Rows[introws]["column_name"] + "=" + dt.Rows[introws][0], sQLcONN);
MySqlCommand sqlCmd = new MySqlCommand("update " + strTableName + "set " + dtColumn.Rows[introws]["column_name"] + "=#value1 where " + dtColumn.Rows[introws]["column_name"] + "=#value2", sQLcONN);
sqlCmd.Parameters.AddWithValue("#value1", "txtTextBox + dt.Rows[introws][0].ToString()");
sqlCmd.Parameters.AddWithValue("#value2",dt.Rows[introws][0]);
MySqlDataAdapter sqlDa = new MySqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Write("Succesfully updated");
}
else
{
Response.Write("Error");
}
}
}
Given the following code to export each table in the database:
string strSql = "SELECT * FROM " + tableName;
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dbPath);
using (SqliteCommand sqlComm = new SqliteCommand(strSql, sqlCon) { CommandType = CommandType.Text })
{
var da = new SqliteDataAdapter(sqlComm);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Tables[0].WriteXml(Path.Combine(syncPath, tableName + "_4.xml"));
}
I'm trying to import the XML back into the database with the following:
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dataPath + "/Empty.db3");
sqlCon.Open();
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine(syncPath, tableName + "_4.xml"));
DataTable dt = ds.Tables[0];
string keyField = dt.Columns[0].ColumnName;
dt.PrimaryKey = new DataColumn[] { dt.Columns[keyField] };
var adapterForTable1 = new SqliteDataAdapter("Select * from " + tableName, sqlCon);
adapterForTable1.AcceptChangesDuringFill = false;
var builderForTable1 = new SqliteCommandBuilder(adapterForTable1);
adapterForTable1.Update(ds, tableName);
sqlCon.Close();
But I get the error: Dynamic SQL generation is not supported with no base table. How do I fix this?
Abandoned the Update option and wrote this:
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dataPath + "/Empty.db3");
sqlCon.Open();
SqliteCommand sqlCmd = new SqliteCommand(sqlCon);
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine(syncPath, tableName + "_4.xml"), XmlReadMode.ReadSchema);
foreach(DataTable dt in ds.Tables)
{
//Get field names
string sqlString = "INSERT into " + tableName + " (";
string valString = "";
var sqlParams = new string[dt.Rows[0].ItemArray.Count()];
int count = 0;
foreach(DataColumn dc in dt.Columns)
{
sqlString += dc.ColumnName + ", ";
valString += "#" + dc.ColumnName + ", ";
sqlParams[count] = "#" + dc.ColumnName;
count++;
}
valString = valString.Substring(0, valString.Length - 2);
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ") VALUES (" + valString + ")";
sqlCmd.CommandText = sqlString;
foreach(DataRow dr in dt.Rows)
{
for (int i = 0; i < dr.ItemArray.Count(); i++)
{
sqlCmd.Parameters.AddWithValue(sqlParams[i], dr.ItemArray[i] ?? DBNull.Value);
}
sqlCmd.ExecuteNonQuery();
}
}