Import data from SQLite to SQL Server with SqlBulkCopy class - sqlite

I'm trying to transfer the data from SQLite to SQL Server. The schema of target and destination table are just the same:
SQL Server:
CREATE TABLE [dbo].[Shop] (
[ShopID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](128) NOT NULL,
[Url] [nvarchar](128) NOT NULL,
PRIMARY KEY CLUSTERED
(
[ShopID] ASC
))
and SQLite:
CREATE TABLE "Shop" (
"ShopID" INTEGER PRIMARY KEY NOT NULL,
"Name" VARCHAR NOT NULL,
"Url" VARCHAR NOT NULL);
I wrote the code as below (with System.Data.SQLite):
using (var conn = new SQLiteConnection(#"Data Source=Data.sqlite;FailIfMissing=True"))
{
conn.Open();
var cmd = new SQLiteCommand("SELECT * FROM Shop", conn);
var reader = cmd.ExecuteReader();
using (var bulkCopy = new SqlBulkCopy("Data Source=.;Initial Catalog=Test;Integrated Security=True"))
{
bulkCopy.DestinationTableName = "Shop";
bulkCopy.ColumnMappings.Add("ShopID", "ShopID");
bulkCopy.ColumnMappings.Add("Name", "Name");
bulkCopy.ColumnMappings.Add("Url", "Url");
bulkCopy.WriteToServer(reader);
}
}
Data has been loaded by reader (I've checked). But an InvalidOperationException throws on WriteToServer method: The given ColumnMapping does not match up with any column in the source or destination.
Any ideas or suggestion for me?

This may or may not solve your problem, but you probably want to use the SqlBulkCopyOptions to specify that you don't want it to generate new identity values.
SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))

This works for me...
private void GatherDb3Info(FileInfo[] fiDb3) {
SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder();
foreach (FileInfo fi in fiDb3) {
csb.Clear();
csb.DataSource = fi.FullName;
csb.Password = "P#$$w0rd";
csb.SyncMode = SynchronizationModes.Full;
using (var conn = new SQLiteConnection(csb.ToString())) {
conn.Open();
DataTable dtTables = conn.GetSchema(SQLiteMetaDataCollectionNames.Tables, new String[] { });
foreach (DataRow dRow in dtTables.Rows) {
if (dRow["Table_Type"].ToString().ToLower() != "table") continue;
String
catName = String.Format("{0}", dRow["Table_Catalog"]),
schName = String.Format("{0}", dRow["Table_Schema"]),
tblName = String.Format("{0}", dRow["Table_Name"]);
DataTable dtColumns = conn.GetSchema(SQLiteMetaDataCollectionNames.Columns, new System.String[] { catName, schName, tblName });
StringBuilder sb = new StringBuilder();
foreach (DataRow dRowColumn in dtColumns.Rows) {
sb.AppendFormat("[{0}], ", dRowColumn["Column_Name"]);
}
String sColList = sb.ToString();
sColList = sColList.Remove(sColList.Length - 2);
var cmd = new SQLiteCommand("Select " + sColList + " From " + tblName, conn);
var reader = cmd.ExecuteReader();
using (var bulkCopy = new System.Data.SqlClient.SqlBulkCopy(#"Server=.;Integrated Security=true;Database=TargetDBName;")) {
bulkCopy.DestinationTableName = "TargetTableSchema." + tblName;
try {
bulkCopy.WriteToServer(reader);
} catch (Exception) { }
}
}
conn.Close();
}
}
}

Related

Inserting dynamics 365 records into SQL Server database using asp.net

I am currently working on a project to insert a list of records from a dynamics 365 website into to a SQL Server database. However when I call the class file no insert is currently made into the database.
Can someone assist me? I have placed an ellipsis at the where the code which pulls the data from crm would be as that code works fine and so what you're reading isn't as long. Let me know if it is needed.
public class ProgramPVT
{
static void Main (string[] args)
{
try
{
...
int count = 0;
int n = count;
foreach (var item in performancevt)
{
performancevt.Add(item);
}
var totalnumber = performancevt.Count;
var t = totalnumber;
var accountmanager = new string[t];
var monthlytarget = new string[t];
var forecast_ = new string[t];
var actual_ = new string[t];
var managedservices = new string[t];
var pvtpercentage_ = new string[t];
var mspercentage_ = new string[t];
SqlConnection crmdbconnection = new SqlConnection("Data Source =*****;Initial Catalog=****;User Id = ******;Password = ******;");
crmdbconnection.Open();
foreach (var performanceitem in performancevt)
{
accountmanager[n] = performanceitem.accountmanager.ToString();
monthlytarget[n] = performanceitem.monthlytarget.ToString();
forecast_[n] = performanceitem.accountmanager.ToString();
actual_[n] = performanceitem.accountmanager.ToString();
managedservices[n] = performanceitem.monthlytarget.ToString();
pvtpercentage_[n] = performanceitem.accountmanager.ToString();
mspercentage_[n] = performanceitem.accountmanager.ToString();
var i = 0;
do
{
try
{
string cmdtext = "INSERT INTO PerformanceVTarget (Account_Manager, Month_Target, Forecast, Achieved, Total_Percentage, MS_Percentage) VALUES (#Account_Manager, #Month_Target, #Forecast, #Achieved, #Total_Percentage, #MS_Percentage)";
using (var cmd = new SqlCommand(cmdtext, crmdbconnection))
{
{
cmd.Parameters.AddWithValue("#Account_Manager", accountmanager[n]);
cmd.Parameters.AddWithValue("#Month_Target", accountmanager[n]);
cmd.Parameters.AddWithValue("#Forecast", accountmanager[n]);
cmd.Parameters.AddWithValue("#Achieved", accountmanager[n]);
cmd.Parameters.AddWithValue("#Total_Percentage", accountmanager[n]);
cmd.Parameters.AddWithValue("#Account_Manager", accountmanager[n]);
}
cmd.ExecuteNonQuery();
}
}
catch (Exception fx)
{
Console.Write(fx);
Console.WriteLine("Line with ID:", n, " not inserted");
Console.WriteLine("Error - Press enter to Continue");
Console.ReadLine();
}
i++;
} while (i < t);
}
n = n + 1;
}
catch (Exception ex)
{
Console.Write(ex);
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
}
}
}
}
Table PerformanceVTarget
[ID] pk, int ,not null
[Report_ID] int, null
[Account_Manager] varchar(50) not null
[Month_Target] varchar(50) not null
[Forecast] varchar(50) not null
[Achieved] varchar(50) not null
[Total_Percentage] varchar(50) not null
[MS_Percentage] varchar(50) not null
[Team] varchar(50) null
Your code execution will never come out of this loop.
foreach (var item in performancevt)
{
performancevt.Add(item);
}
This is a deadlock or you should get an error.
Also you are not passing any value to [MS_Percentage] & Id (primary key field), both are non-null columns.

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

ASP.NET C# - Redirect After Inserted Record

I perform and insert new record, this code below works for for inserting. After that, I want to redirect to another page using window.parent.location with the ID (ProposalID) that I used in the insert.
private void ExecuteInsert(string ProposedID, string CreatedBy, string Note)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_ProposedNote (ProposedID, Note, CreatedBy)
VALUES "
+ " (#ProposedID, #Note, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ProposedID", SqlDbType.Int, 10);
param[1] = new SqlParameter("#Note", SqlDbType.VarChar, 2000);
param[2] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = ProposedID;
param[1].Value = Note;
param[2].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
}
}
This is where I and to redirect to another page + RecordID
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
Please help. Thanks in advance.
You probably want
Response.Redirect(string.format("~/ProposalItemView.aspx?ProposedID={0}", ProposedID), true);

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

Insert ADO.Net DataTable into an SQL table

The current solution i implemented is awful!
I use a for... loop for inserting records from an ADO.NET data-table into an SQL table.
I would like to insert at once the data-table into the SQL table, without iterating...
Is that possible, or am i asking too much?
You can pass the entire DataTable as a single Table Valued Parameter and insert the entire TVP at once. The following is the example from Table-Valued Parameters in SQL Server 2008 (ADO.NET):
// Assumes connection is an open SqlConnection.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(
DataRowState.Added);
// Define the INSERT-SELECT statement.
string sqlInsert =
"INSERT INTO dbo.Categories (CategoryID, CategoryName)"
+ " SELECT nc.CategoryID, nc.CategoryName"
+ " FROM #tvpNewCategories AS nc;"
// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(
sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
"#tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.CategoryTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
}
TVP are only available in SQL 2008.
I think you are looking for SQLBulkCopy.
SqlBulkCopy is the simplest solution.
using (SqlConnection dbConn = new SqlConnection(connectionString))
{
dbConn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dbConn))
{
bulkCopy.DestinationTableName =
"dbo.MyTable";
try
{
bulkCopy.WriteToServer(myDataTable, DataRowState.Added);
}
catch (Exception ex)
{
myLogger.Error("Fail to upload session data. ", ex);
}
}
}
You can create SqlBulkCopyColumnMapping if the columns in your DataTable don't match your database table.
You can also try the following method.
private void button1_Click(object sender, EventArgs e)
{
tabevent();
DataSet ds = new DataSet();
DataTable table = new DataTable("DataFromDGV");
ds.Tables.Add(table);
foreach (DataGridViewColumn col in dataGridView1.Columns)
table.Columns.Add(col.HeaderText, typeof(string));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
table.Rows.Add(row);
foreach (DataGridViewCell cell in row.Cells)
{
table.Rows[row.Index][cell.ColumnIndex] = cell.Value;
}
}
// DataTable ds1changes = ds1.Tables[0].GetChanges();
if (table != null)
{
SqlConnection dbConn = new SqlConnection(#"Data Source=wsswe;Initial Catalog=vb;User ID=sa;Password=12345");
SqlCommand dbCommand = new SqlCommand();
dbCommand.Connection = dbConn;
foreach (DataRow row in table.Rows)
{
if (row["quantity"] != null && row["amount"]!=null && row["itemname"]!=null)
{
if (row["amount"].ToString() != string.Empty)
{
dbCommand.CommandText =
"INSERT INTO Bill" +
"(Itemname,Participants,rate,Quantity,Amount)" +
"SELECT '" + Convert.ToString(row["itemname"]) + "' AS Itemname,'" + Convert.ToString(row["Partcipants"]) + "' AS Participants,'" + Convert.ToInt32(row["rate"]) + "' AS rate,'" +
Convert.ToInt32(row["quantity"]) + "' AS Quantity,'" + Convert.ToInt32(row["amount"]) + "' AS Amount";
dbCommand.Connection.Open();
dbCommand.ExecuteNonQuery();
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
MessageBox.Show("inserted");
}
}
}
}
}

Resources