Export csv file to sqlite 3 database using sharpssh and c# - c#

Hi I am newbie to c# and sharpssh I am trying to export a csv file to sqlite3 database to external device called explor. I have managed to export csv file to local sqlite3 database and able to connect to database using sharpssh to external device but I want to do both at same time. 1)connect to external device 2)export csv file to database/table on the device. Any help would be greatly appreciated.
1.Connection through SHARPSSH
string _ftpURL = #"192.178.0.77"; //(FAKE IP)
string _UserName = "root"; //FAKE User Name of the SFTP server
string _Password = "preethi"; //FAKE Password of the SFTP server
int _Port = 2222; //Port No of the SFTP server (if any)
string _ftpDirectory = "/home/root/systools/WM/WebMobility.db"; //The directory in SFTP server where the files will be uploaded
string LocalDirectory = "I:\\preethi"; //Local directory from where the files will be uploaded
string FileName = "exploretest.csv"; //File name, which one will be uploaded
// IPHostEntry ip = Dns.GetHostEntry(#"1.1.1.2");
Sftp Connection = new Sftp(_ftpURL,_UserName, _Password);
Connection.Connect(_Port);
EXPORTING the CSV FILE
string strFileName = "I:/preethi/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
//SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data source = 19.9.9.3; port=2222; database = WebMobility.db; uid=root; pwd=preethi; Convert Zero Datetime=true;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "','" + VRM + "'," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();

Related

Problems trying to read dbf file in C#

I am trying to read a dbf file in C#, but first I had the error
System.InvalidOperationException: 'The provider' Microsoft.ACE.OLEDB.12.0 'is not registered on the local machine.'
Then I installed Microsoft Access Database Engine 2010 Redistributable and now I have the error
The Microsoft Access database engine cannot open or write to the file 'C:\Users\Emmanuel\Desktop\Proyectos\program'. It is already opened exclusively by another user, or you need permission to view and write its data.'
This is the code I'm using:
var constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
var sql = "select * from " + file;
var ds = new DataTable();
using (var con = new OleDbConnection(constr))
{
con.Open();
using (var cmd = new OleDbCommand(sql, con))
{
using (var da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Also I've tried this but I have this error
System.Data.Odbc.OdbcException: 'ERROR [HY000] [Microsoft] [ODBC dBase Driver] The external table is not in the expected format.'
string fullPath = path + file;
string sConn = "Driver={Microsoft dBASE Driver (*.dbf)};SourceType=DBF;SourceDB=" + path + ";Exclusive=No; NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
using (OdbcConnection dbConn = new OdbcConnection(sConn))
{
dbConn.Open();
OdbcCommand oCmd = dbConn.CreateCommand();
oCmd.CommandText = "SELECT * FROM " + fullPath;
/* Load data to table */
DataTable dt1 = new DataTable();
dt1.Load(oCmd.ExecuteReader());
dbConn.Close();
}

Excel File Reading External table is not in the expected format

I am generating excel file with JS,then uploading it in a temporary folder then reading it after uploading.Its giving me error " External table is not in the expected format." when I am trying to read the generated Excel file(its in xls fomat,same as with xlsx), If I make excel file in MS Excel and read it,its working fine
This is how I am generating
function GenerateExcel() {
var tab_text = $("#hdnUserData").val();
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Users Report.xls");
//sa = txtArea1.document.execCommand('SaveAs', true, 'Error Report.xsl');
}
else//other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
the excel data in columns like this
UserID Name Username
and hidden field have data in CSV like this
1,Test,test123;2,myuser,muser1
This is how I am reading excel
using (var conn = new OleDbConnection())
{
var dt = new DataTable("dtExcel");
string importFileName = path;//Path of uploaded excel file with filename
string fileExtension = System.IO.Path.GetExtension(importFileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + importFileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + importFileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'";
conn.Open();
DataTable dtSheets = conn.GetSchema("Tables");
string firstSheet = dtSheets.Rows[0]["TABLE_NAME"].ToString();
using (var comm = new OleDbCommand())
{
comm.CommandText = "select * from [" + firstSheet + "]";
comm.Connection = conn;
using (var da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
}
}
}
any alternative approach for reading?I have tried with stream but same error.
Error is appearing at con.Open()

Import Data from .csv to SQL Server using File Upload in Asp.net C#

I have an .csv file which I upload it through a FileUpload control and I want to transfer the whole data from that csv file into a SQL Server database table, but I have some problems in my code:
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("EmailId");
string path = System.IO.Path.GetFileName(fupEmails.PostedFile.FileName);
fupEmails.PostedFile.SaveAs(Server.MapPath("~/Contacts/" + path));
path = Server.MapPath("~/Contacts/" + path);
TextFieldParser csvParser = new TextFieldParser(path);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
//csvParser.ReadLine();
while (!csvParser.EndOfData)
{
string[] fields = csvParser.ReadFields();
tblReadCSV.Rows.Add(fields.Equals("Email"));
}
string connection = #"Data Source=ANURAG-PC; Initial Catalog=MailServer; Persist Security Info=True; User ID=sa; Password=anurag";
string strSql = "Insert into EmailData(EmailId) Values(#Email)";
SqlConnection con=new SqlConnection(connection);
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.Text;
cmd.CommandText=strSql;
cmd.Connection=con;
cmd.Parameters.Add("#Email",SqlDbType.NVarChar,250,"Email");
SqlDataAdapter daAdapter=new SqlDataAdapter();
daAdapter.InsertCommand=cmd;
int result=daAdapter.Update(tblReadCSV);
lblError.Text="Send Successfully";
and I'm getting error in the second last line
int result = daAdapter.Update(tblReadCSV);
and the error is
The parameterized query '(#Email nvarchar(250))Insert into EmailData(EmailId) Values(#Ema' expects the parameter '#Email', which was not supplied.
cmd.Parameters.Add("#Email",SqlDbType.NVarChar,250,"EmailId");
The name of the column you added to the DataTable was EmailId, not Email.

data import from excel facing an issue

I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>

Import excel file which is on local machine to SQL server 2005

I have a path to an Excel file which is located on my local machine and I want to import the data of the Excel file to SQL Server 2005.
I have tried this code but it gives me an error:
string sSourceConStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + textBox1 + "; Extended Properties=" + "\"Excel 8.0;HDR=YES;+\"";
string dDestConStr = #"server=severIPAddress;database=databaseName;uid=userName;password=pwd";
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConStr);
using (sSourceConnection)
{
string sql = string.Format("Select * FROM [{0}]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dDestConStr))
{
bulkCopy.DestinationTableName = "dbo.databaseName";
bulkCopy.WriteToServer(dr);
}
}
}
Error:
OleDBException was unhandled. Failure creating file.
What would cause this and how can I resolve it?
Change textBox1 to textBox1.Text in Data Source

Categories