Backup SQL Server database by C# statement - c#

I want to create a backup for the database I worked on my application by C# statement.
This is my code:
SqlConnection con = new SqlConnection(Connection.GetConnection());
SqlCommand command = new SqlCommand();
command.CommandText = "backup database [Pharmacy Database]to disk ="+"'"+path +"'";
command.CommandType = CommandType.Text;
command.Connection = con;
con.Open();
command.ExecuteNonQuery();
con.Close();
And gives me an error:
Cannot open backup device 'C:/Users/Abo Sala7/Desktop'.Operating system error 5 (failed to retrieve text for this error. Reason:15105).
BACKUP DATABASE is terminating abnormally.

Maybe the Problem is that your ServiceUser of the SQL-Service does not have the permission to write into the defined folder - The service is perfoming the backup - so this user must have the requiered permissions on the destination folder. (error 5 == Accessdenied)

I have been using the code below for back up, try this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Backups the data base.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public bool BackupDataBase(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return false;
bool isDatabackedUp = true;
try
{
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
BackupDeviceItem deviceItem = new BackupDeviceItem(fileName, DeviceType.File);
ServerConnection connection = new ServerConnection(this.BackupConnection);
DataConnection dataConnection = new DataConnection();
Server sqlServer = new Server(dataConnection.ServerName);
Database db = sqlServer.Databases[dataConnection.DataBaseName];
sqlBackup.Database = dataConnection.DataBaseName;
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
return isDatabackedUp;
}
catch (Exception)
{
return false;
}
}
private SqlConnection BackupConnection
{
get
{
string backupConnectionString = string.Empty;
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["LibrarySystemBackUpConnection"];
backupConnectionString = settings.ConnectionString;
SqlConnection backupDatabaseConnection = new SqlConnection(backupConnectionString);
return backupDatabaseConnection;
}
}

Here is a procedure is use for back up in C#.Hope it helps
public void BackupDatabase
(string BackUpLocation, string BackUpFileName, string DatabaseName, string ServerName )
{
DatabaseName = "[" + DatabaseName + "]";
string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;
BackUpFileName = BackUpFileName + fileUNQ + ".bak";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + #"\" + BackUpFileName + #"'";
string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
try
{
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Label1.Text = "Done";
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk .Close();
}
}
}

internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(#"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(#"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}

Related

How to upload a DB backup to a FTP server

On the tail end of database backup project and I've run into a issue where the Deflate compression I put in can't seem to find the path I saved the backup to. Being that the default backup location (used here) is on a network drive is there something else I need to do to make sure the path is found by Deflate? As of now I get System.IO.DirectoryNotFoundException: 'Could not find a part of the path. The purpose of the tool is to be able to put in any server you want to access, get a list of available DB's and then choose the one you want to backup.
I had this issue before locally, but all i had to do was give SQLserver the proper permissions to the folder.
using (SqlConnection newConn = new SqlConnection(connString))
using (SqlCommand sqlCmd = new SqlCommand(query, newConn))
{
newConn.Open();
value = sqlCmd.ExecuteScalar();
canCompress = !(value == null || Convert.ToInt32(value) == 0);
//----------------------------------
//SQL Commands to run backup process
//----------------------------------
Interface.WriteLine("Creating backup");
if (canCompress)
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, COMPRESSION, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
else
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
//----------------------------------
//Grab Backup File
//----------------------------------
query = "SELECT physical_device_name "
+ "FROM msdb.dbo.backupset b "
+ "JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id "
+ "WHERE database_name = '" + connBuilder.InitialCatalog + "' "
+ "ORDER BY backup_finish_date DESC ";
using (SqlConnection connection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
value = cmd.ExecuteScalar();
if (value != null)
backupFile = (string)value;
else
throw new Exception("Unable to find backup file.");
}
//Set which files should be uploaded.
if (canCompress)
{
fileToUpload = backupFile;
}
else
{
fileToUpload = Deflate.CompressFile(backupFile); //Point of error message
File.Delete(backupFile);
}
return fileToUpload;
}
static class Deflate
{
public static string CompressFile(string sourcePath, string destPath = null)
{
if (destPath == null)
destPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".cmp");
using (FileStream originalFileStream = File.OpenRead(sourcePath))
using (FileStream compressedFileStream = File.Create(destPath))
using (DeflateStream compressionStream = new
DeflateStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
compressedFileStream.Flush();
}
FileInfo sourceInfo = new FileInfo(sourcePath); //Remove the .bak extension on compression?
FileInfo destInfo = new FileInfo(destPath); //Remove the .bak extension on compression?
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", Path.GetFileName(sourcePath), sourcePath.Length, destInfo.Length);
return destPath;
}
}

Slow performance importing MS Access database into SQL Server

I have a problem with importing items from an MS Access .mdb database file into SQL Server. I wrote a C# application in practice database that extrapolates the data in a .mdb database and places them in a table in a SQL Server database.
My problem is that the .mdb database contains about 300,000 articles which are to be inserted with all of the controls inside the SQL Server database. The .mdb file is selected by the user.
How can I speed up the import of the articles?
This is my C# code:
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
// SqlConnection conn2 = db.apriconnessione();
try
{
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
string querycontalinee = "SELECT count(*) from ARTICOLI";
OleDbCommand command = new OleDbCommand(query, dbConn);
OleDbCommand commandcontalinee = new OleDbCommand(querycontalinee, dbConn);
dbConn.Open();
int linee = (int)commandcontalinee.ExecuteScalar();
OleDbDataReader reader = command.ExecuteReader();
Articolo a;
labelstatoaggiornamento.Show();
progressBarstatoaggiornamento.Show();
progressBarstatoaggiornamento.Style = ProgressBarStyle.Continuous;
progressBarstatoaggiornamento.Minimum = 0;
progressBarstatoaggiornamento.Maximum = linee;
progressBarstatoaggiornamento.Step = 1;
SqlConnection conn = db.apriconnessione();
while (reader.Read())
{
String CodMarca = "" + reader.GetValue(0).ToString();
String CodArt = "" + reader.GetValue(1).ToString().Replace("'", ""); ;
String Fornitore = "COMET";
String Descrizione = "" + reader.GetValue(2).ToString();
String UM = "" + reader.GetValue(3).ToString();
String PrezzoNetto = "" + reader.GetValue(4).ToString();
String PrezzoCasa = "" + reader.GetValue(5).ToString();
DateTime DataAggiornamento = DateTime.Now;
decimal Prezzo = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
decimal PrezzoListino = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
a = new Articolo(CodArt, CodMarca);
a.db = db;
if (a.ControlloDisponibilitàCOMET() == true)
{
string queryAggiornamento = "Update Articolo Set Descrizione='" + Descrizione + "', UM='" + UM + "', Prezzo='" + Prezzo + "',PrezzoListino='" + PrezzoListino + "',DataAggiornamento='" + DataAggiornamento + "',Stato='Aggiornamentoincorso' Where CodMarca = '" + CodMarca + "' AND CodArt = '" + CodArt + "' AND Importato = 'COMET' and Fornitore='COMET' ";
SqlCommand commaggiorna = new SqlCommand(queryAggiornamento, conn);
try
{
commaggiorna.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(" " + ex);
}
}
else
{
string query2 = "INSERT INTO Articolo (CodMarca, CodArt, Fornitore, Importato, Descrizione, UM, Prezzo, PrezzoListino, Stato) VALUES (#CodMarca, #CodArt, #Fornitore, #Importato, #Descrizione, #UM, #Prezzo, #PrezzoListino, #Stato)";
SqlCommand myCommand = new SqlCommand(query2, conn);
myCommand.Parameters.AddWithValue("#CodMarca", CodMarca);
myCommand.Parameters.AddWithValue("#CodArt", CodArt);
myCommand.Parameters.AddWithValue("#Fornitore", Fornitore);
myCommand.Parameters.AddWithValue("#Importato", Fornitore);
myCommand.Parameters.AddWithValue("#Descrizione", Descrizione);
myCommand.Parameters.AddWithValue("#UM", UM);
decimal PrezzoNetto2 = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#Prezzo", PrezzoNetto2);
decimal PrezzoCasa2 = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#PrezzoListino", PrezzoCasa2);
DateTime dt = Convert.ToDateTime(DataAggiornamento);
myCommand.Parameters.AddWithValue("#Stato", "Aggiornamentoincorso");
myCommand.ExecuteNonQuery();
}
progressBarstatoaggiornamento.PerformStep();
int percent = (int)(((double)progressBarstatoaggiornamento.Value / (double)progressBarstatoaggiornamento.Maximum) * 100);
progressBarstatoaggiornamento.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBarstatoaggiornamento.Width / 2 - 10, progressBarstatoaggiornamento.Height / 2 - 7));
}
string queryNonDisponibili = "Update Articolo Set Stato='Nondisponibile' where Stato!='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
string queryNonDisponibili2 = "Update Articolo Set Stato='Disponibile' where Stato='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
SqlCommand comm = new SqlCommand(queryNonDisponibili, conn);
SqlCommand comm2 = new SqlCommand(queryNonDisponibili2, conn);
comm.ExecuteNonQuery();
comm2.ExecuteNonQuery();
Console.WriteLine("\n Passaggio Completato");
conn.Close();
db.chiudiconnessione();
dbConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("La password è errata oppure " + ex);
}
Consider using SqlBulkCopy. Since you are running sql queries I would suggest you'd work server side as much as possible. Create a temp table in Sql Server, add all records to a datatable or array of datarows and use SqlBulkCopy to import. I think that is the fastest way to move all records to Sql Server.
From there you can synchronize the two tables in Sql Server with only a few queries.
I would use SqlBulkCopy ...
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
SqlConnection conn2 = db.apriconnessione();
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
OleDbDataAdapter da = new OleDbDataAdapter(query,dbConn);
DataTable dt = new DataTable();
da.Fill(dt);
conn2.Open();
SqlBulkCopy bulk = new SqlBulkCopy(conn2);
bulk.DestinationTableName = "ARTICOLI";
bulk.WriteToServer(dt);
conn2.close();

C# to store data into MS-Access database

I need to write C# code to insert data into an MS-Access database. The program adds it but if I close the application the database resets.
database is in the debug x86 folder
Here is my code for adding data
provider = "Provider=Microsoft.ACE.OLEDB.12.0";
applicatiePad = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"));
pad = "Data Source=" + applicatiePad + "/Geluidsfragmentendb.accdb";
connectionString = provider + ";" + pad;
connection = new OleDbConnection(connectionString);
...
public bool VoegToe(int geluidsfragmentnr,
string Titel,
string bestandsnaam,
int min,
int sec)
{
string time = min + ":" + sec;
DateTime tijd = Convert.ToDateTime(time);
String voegGfToe = "INSERT INTO Geluidsfragment (GeluidsfragmentID, Titel, bestandsnaam, tijdsduur) VALUES (" + geluidsfragmentnr + ",'" + Titel + "'" + ",'"+ bestandsnaam + "','" + tijd + "')";
OleDbCommand command = new OleDbCommand(voegGfToe, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch ( Exception e)
{
MessageBox.Show(e.Message);
return false;
}
finally
{
connection.Close();
}
}

How to convert a CSV file to MDB (Access Database) using C# [duplicate]

using C# I am trying to create a console app that reads a CSV file from a specific folder location and import these records into a MS Access Table. Once the records in the file have been imported successfully I will then delete the .csv file.
So far this is what I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
namespace QuantumTester
{
class Program
{
static void Main(string[] args)
{
CsvFileToDatatable(ConfigurationManager.AppSettings["CSVFile"], true);
}
public static DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not
{
string header = "Yes"; //"No" if 1st row is not header cols
string sql = string.Empty;
DataTable dataTable = null;
string pathOnly = string.Empty;
string fileName = string.Empty;
try
{
pathOnly = Path.GetDirectoryName(ConfigurationManager.AppSettings["QuantumOutputFilesLocation"]);
fileName = Path.GetFileName(ConfigurationManager.AppSettings["CSVFilename"]);
sql = #"SELECT * FROM [" + fileName + "]";
if (IsFirstRowHeader)
{
header = "Yes";
}
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
}
}
}
}
finally
{
}
return dataTable;
}
}
}
Can I just go ahead an save the datatable to a table I have created in the Access DB? How would I go about doing this? Any help would be great
You can run a query agains an Access connection that creates a new table from a CSV file or appends to an exisiting table.
The SQL to create a table would be similar to:
SELECT * INTO NewAccess
FROM [Text;FMT=Delimited;HDR=NO;DATABASE=Z:\Docs].[Table1.csv]
To append to a table:
INSERT INTO NewAccess
SELECT * FROM [Text;FMT=Delimited;HDR=NO;DATABASE=Z:\Docs].[Table1.csv]
finally got this working and this is what I have - hope it helps someone else in the future:
public static DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not
{
string header = "Yes"; //"No" if 1st row is not header cols
string query = string.Empty;
DataTable dataTable = null;
string filePath = string.Empty;
string fileName = string.Empty;
try
{
//csv file directory
filePath = Path.GetDirectoryName(ConfigurationManager.AppSettings["QuantumOutputFilesLocation"]);
//csv file name
fileName = Path.GetFileName(ConfigurationManager.AppSettings["CSVFilename"]);
query = #"SELECT * FROM [" + fileName + "]";
if (IsFirstRowHeader) header = "Yes";
using (OleDbConnection connection = new OleDbConnection((#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Text;HDR=" + header + "\"")))
{
using (OleDbCommand command = new OleDbCommand(query, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
adapter.Fill(dataTable);
//create connection to Access DB
OleDbConnection DBconn = new OleDbConnection(ConfigurationManager.ConnectionStrings["Seagoe_QuantumConnectionString"].ConnectionString);
OleDbCommand cmd = new OleDbCommand();
//set cmd settings
cmd.Connection = DBconn;
cmd.CommandType = CommandType.Text;
//open DB connection
DBconn.Open();
//read each row in the Datatable and insert that record into the DB
for (int i = 0; i < dataTable.Rows.Count; i++)
{
cmd.CommandText = "INSERT INTO tblQuantum (DateEntered, Series, SerialNumber, YearCode, ModelNumber, BatchNumber, DeviceType, RatedPower, EnergyStorageCapacity," +
"MaxEnergyStorageCapacity, User_IF_FWRevNo, Charge_Controller_FWRevNo, RF_Module_FWRevNo, SSEGroupNumber, TariffSetting)" +
" VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) +
"','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) +
"','" + dataTable.Rows[i].ItemArray.GetValue(6) + "','" + dataTable.Rows[i].ItemArray.GetValue(7) + "','" + dataTable.Rows[i].ItemArray.GetValue(8) +
"','" + dataTable.Rows[i].ItemArray.GetValue(9) + "','" + dataTable.Rows[i].ItemArray.GetValue(10) + "','" + dataTable.Rows[i].ItemArray.GetValue(11) +
"','" + dataTable.Rows[i].ItemArray.GetValue(12) + "','" + dataTable.Rows[i].ItemArray.GetValue(13) + "','" + dataTable.Rows[i].ItemArray.GetValue(14) + "')";
cmd.ExecuteNonQuery();
}
//close DB.connection
DBconn.Close();
}
}
}
}
finally
{
}
return dataTable;
}

how to insert data if it contain apostrophe?

Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace tool
{
public partial class Form1 : Form
{
StreamReader reader;
SqlConnection con;
SqlCommand cmd;
int count = 0;
//int id=0;
FileStream fs;
string file = null;
string file_path = null;
SqlCommand sql_del = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog();
file1.ShowDialog();
textBox1.Text = file1.FileName.ToString();
file = Path.GetFileName(textBox1.Text);
file_path = textBox1.Text;
fs = new FileStream(file_path, FileMode.Open, FileAccess.Read);
}
private void button2_Click(object sender, EventArgs e)
{
if (file != null )
{
sql_del = new SqlCommand("Delete From credit_debit1", con);
sql_del.ExecuteNonQuery();
reader = new StreamReader(file_path);
string line_content = null;
string[] items = new string[] { };
while ((line_content = reader.ReadLine()) != null)
{
if (count >=4680)
{
items = line_content.Split(',');
string region = items[0].Trim('"');
string station = items[1].Trim('"');
string ponumber = items[2].Trim('"');
string invoicenumber = items[3].Trim('"');
string invoicetype = items[4].Trim('"');
string filern = items[5].Trim('"');
string client = items[6].Trim('"');
string origin = items[7].Trim('"');
string destination = items[8].Trim('"');
string agingdate = items[9].Trim('"');
string activitydate = items[10].Trim('"');
if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber)))
{
invoicenumber = "null";
}
else
{
invoicenumber = "'" + invoicenumber + "'";
}
if ((destination == "-") || (string.IsNullOrEmpty(destination)))
{
destination = "null";
}
else
{
destination = "'" + destination + "'";
}
string vendornumber = items[11].Trim('"');
string vendorname = items[12].Trim('"');
string vendorsite = items[13].Trim('"');
string vendorref = items[14].Trim('"');
string subaccount = items[15].Trim('"');
string osdaye = items[16].Trim('"');
string osaa = items[17].Trim('"');
string osda = items[18].Trim('"');
string our = items[19].Trim('"');
string squery = "INSERT INTO credit_debit1" +
"([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " +
"[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " +
"[OverUnderRecovery] ) " +
"VALUES " +
"('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," +
"'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," +
"'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') ";
cmd = new SqlCommand(squery, con);
cmd.CommandTimeout = 1500;
cmd.ExecuteNonQuery();
}
label2.Text = count.ToString();
Application.DoEvents();
count++;
}
MessageBox.Show("Process completed");
}
else
{
MessageBox.Show("path select");
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;");
con.Open();
}
}
}
vendername field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data
Use prepared statements, in this case SqlParameterCollection.AddWithValue or equivalent. There are a variety of tutorials available for this.
You are very naughty for building your sql statements that way, Santa Claus is definitely not going to visit you this year. Doing queries the way you are is opening yourself to sql injection attacks, intentional and unintentional as you've discovered with the '.
You should use parameterized query strings or stored procedures.
const string connString = "Data Source=localhost;Initial Catalog=OnlineQuiz;Integrated Security=True";
static void Main(string[] args)
{
string query = string.Format("SELECT * FROM [User] WHERE name like #name");
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#name", "F%");
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetValue(1));
}
}
}
}
}
You need to escape the apostrophe by adding a second apostrophe:
vendorname = vendorname.Replace("'", "''");
Disclaimer: Writing a raw SQL statement without using parameters is dangerous. Ideally, you should write a full SQL insert statement with assumed parameters, and instead of concatenating the value directly into the string, pass it in as a parameter:
string parameterizedSQL = "insert into credit_debit1 (id,region,station) values (#count, #region,#station)";
SqlCommand cmd = new SqlCommand(parameterizedSQL, con);
cmd.Parameters.Add("#count", SqlDbType.Int).Value = count;
cmd.Parameters.Add("#region", SqlDbType.VarChar).Value = region;
cmd.Parameters.Add("#station", SqlDbType.VarChar).Value = station;
cmd.ExecuteNonQuery();

Categories

Resources