Importing .DAT file to Database? - c#

How would I go about import/inserting a .DAT file into the database by calling a procedure?
Here's what my file would look like and it has to go into the database in this format.
50 4411902304 1 3 441192304 01/02/2013
Would the process be the same for .DAT file as to xml file?
Here's what I have for xml
SqlConnection myConnection = new SqlConnection("user id=name;" +
"password=password;server=servername;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
var conn = new SqlConnection();
conn.ConnectionString = "user id=idName;" +
"password=password;" + "server=servername;" + "Trusted_Connection=yes;" + "database=databasename; " + "connection timeout=30";
string filePath = "C:/TestData2.xml";
string xml = File.ReadAllText(filePath);
using (SqlConnection con = new SqlConnection(conn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("procedureName"))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#x", xml);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
}

What happens is that XML is a new technology compared to the old flat file (DAT).
XML is a markup format file and there are functions implemented to make easier the importing tasks.
Flat file are older, so a different approach is needed.
You can use the bcp (bulk copy program) to import files to SQL Server or the SSIS Import options.
Or, you can also use:
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\data\TestData2.dat");
int counter = 0;
while ((line = (file.ReadLine())) != null){...}
And parsing each line using the Split command.
string[] fields= line.Split(' ');
string a = fields[0];
string b = fields[1];
string c = fields[2];
and then execute a command to insert each line:
string sqlCommandtoInsert= "INSERT INTO [Table] (Tablefield1, Tablefield2, Tablefield3) VALUES (" + a + ", " + b + ", '" + c + "');";
cmd.CommandText = sqlCommandtoInsert;
cmd.ExecuteNonQuery();
Inserting each record in your table.

Related

How to insert an number value to a oracle db

i have a problem with my code. My code is working fine, but i want to insert a decimal number in my oracle table (the type of the field in oracle is number).
"Gewicht" is a textfield where the user have to type a decimal number in. actually i can insert just full numbers but i cant insert decimal.
my oracle datafields:
TOUR - VARCHAR2 (20 BYTE)
GEWICHT - NUMBER
I have no much experience about programming so i give my best. Its my first Script :).
private void insert()
{
try
{
String connectionString = "Data Source = (DESCRIPTION = " +
"(ADDRESS = (PROTOCOL = TCP)(HOST = IP-Adress)(PORT = 1521))" +
"(CONNECT_DATA =" +
" (SERVER = DEDICATED)" +
" (SERVICE_NAME = NAME)" +
")" +
");User Id = USER;password=password;";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "insert into TABLENAME (TOUR,GEWICHT) values ('" + this.comboBox1.Text + "'," + Gewicht.Text+ ")";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Erfolgreich eingefügt");
comboBox1.Text = String.Empty;
Gewicht.Clear();
viewdata();
}
catch (Exception ex)
{
MessageBox.Show("Fehler");
}
You are missing quotes in your insert query string. In any case, use parameters like:
cmd.CommandText = "insert into TABLENAME (TOUR,GEWICHT) values (#tour,#wicht)";
cmd.Parameters.Add("#tour", OracleDbType.NVarChar2).Value = this.comboBox1.Text;
cmd.Parameters.Add("#wicht", OracleDbType.Decimal).Value = Decimal.Parse(Gewicht.Text);

SELECT ODBC table and INSERT into SQL Server

I have an ODBC connection to a database of which I need one table of data with 10 columns.
I need to insert this table into SQL Server database. I´ve tried to many ways to do it but still with any results.
OdbcConnection OCon = new OdbcConnection("Dsn=" + DbSource.SelectedItem.ToString());
SqlConnection SCon = new SqlConnection("Data Source=" + SrvrDD.SelectedItem.ToString() + ";database=" + DdDestiny.SelectedItem.ToString() + ";User ID=id;Password=pass");
OCon.Open();
SCon.Open();
String QrySelect ="SELECT * FROM " + GridCon.Rows[x].Cells[1].Value;
OdbcCommand commandC = new OdbcCommand(QrySelect, OCon);
String QryInsert = "INSERT INTO " + DdDestiny.SelectedItem.ToString() + ".dbo." + GridCon.Rows[x].Cells[2].Value + " VALUES (#Sql)";
SqlCommand commandD = new SqlCommand(QryInsert, SCon);
OdbcDataReader Oreader = commandC.ExecuteReader();
commandD.Parameters.Add("#Sql",SqlDbType.NVarChar, 5);
while (Oreader.Read())
{
string s = Oreader[0].ToString();
commandD.Parameters["#Sql"].Value = s;
commandD.ExecuteNonQuery();
}
Everything works fine but when commandB.ExecuteNonQuery(); get in, an error appears:
"The column name or the specified values do not correspond to the definition of the table."
Is the translation.

SQLITE - Open two connections (read and write) at once

I have a C# program that needs to read record by record from a DB, then it makes some operations on two columns and then writes on a new column.
So far I did like this:
using (SQLiteConnection conn_write = new SQLiteConnection("Data Source=" + path + ";PRAGMA journal_mode=WAL;"))
{
conn_write.Open();
SQLiteCommand cmd_write = new SQLiteCommand(conn_write);
using (SQLiteConnection conn_read = new SQLiteConnection("Data Source=" + path + ";PRAGMA journal_mode=WAL;"))
{
conn_read.Open();
SQLiteCommand cmd_read = new SQLiteCommand(conn_read);
SQLiteDataReader reader;
sql_read = "SELECT ID, ETRF2000_FI, ETRF2000_LA FROM Tutto_NonAbolito";
cmd_read.CommandText = sql_read;
reader = cmd_read.ExecuteReader();
while (reader.Read())
{
MobileKat.ALCoord.ETRF200ToLL84(reader.GetDouble(reader.GetOrdinal("ETRF2000_FI")), reader.GetDouble(reader.GetOrdinal("ETRF2000_LA")), ref lon, ref lat);
sql_write = "UPDATE Tutto_NonAbolito SET LL84_LON = " + lon + ", LL84_LAT = " + lat + " WHERE " + reader.GetInt32(reader.GetOrdinal("ID")) + " = ID;";
cmd_write.CommandText = sql_write;
cmd_write.ExecuteReader();
}
conn_read.Close();
}
conn_write.Close();
}
I also tried to add PRAGMA but it still tells me that the database file is locked.. Is there a way to do that in this way? I wouldn't like to save the columns in an array and then open another connection. I prefer to do it "on-the-run" if it is possible. Thanks!

Getting Error When Insert in Ms Access 2007 Using c#

I am trying to insert in database Ms Access 2007 . First i get all the file name from folder then copy that file name in database .Here is my Database screenshot.
This is my code
string some = "Nothing";
Response.Write(v);
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
int a =0;
OleDbCommand cmd = new OleDbCommand();
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb";
cmd = mycon.CreateCommand();
mycon.Open();
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = 00 + a.ToString();
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES(" + filename + "," + ips + "," + some + "," +
v + "," + some + "," + some + ");";
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
Response.Write("Writing is complete, Success!");
}
else
{
Response.Write("Application Error, Try Again!");
}
Response.Write(filename+ "<br/>");
}
mycon.Close();
cmd.Dispose();
mycon.Dispose();
I am Getting this error
No value given for one or more required parameters.
In line Line 42: int temp = cmd.ExecuteNonQuery();
If you had used a parameterized query this error would never be seen. The problem is in your string concatenation that lacks of quotes around the string passed for the values in every text/memo field present in your table.
A parameterized query could require more typing but is more readable and will avoid error in parsing values for strings, dates, decimals etc.... (and that big problem called Sql Injection )
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid]," +
"[Description],[title])VALUES(?,?,?,?,?,?)";
cmd.Parameters.AddWithValue("#p1",filename);
cmd.Parameters.AddWithValue("#p2",ips);
cmd.Parameters.AddWithValue("#p3",some);
cmd.Parameters.AddWithValue("#p4",v);
cmd.Parameters.AddWithValue("#p5",some);
cmd.Parameters.AddWithValue("#p6",some);
int temp = cmd.ExecuteNonQuery();

c# application holding file even I've finished work with it

I've got an ado.net code listing:
OleDbConnection oconn = new OleDbConnection();
// oconn.ConnectionString ="Driver={Microsoft Visual FoxPro Driver};Provider=vfpoledb.1;SourceType=DBF;SourceDB=" + pelna_sciezka + ";Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
oconn.ConnectionString = "Provider=vfpoledb.1;Data Source=" + pelna_sciezka + ";Collating Sequence=machine";
oconn.Open();
OleDbCommand ocmd = oconn.CreateCommand();
string na = TBNazwaKonta.Text.Replace("\n","");
na = na.Replace("\r","") ;
string ks2 = ks.Replace("\n","");
ks2 = ks2.Replace("\r", "");
OleDbCommand dbCmdNull = oconn.CreateCommand();
dbCmdNull.CommandText = "SET NULL OFF";
dbCmdNull.ExecuteNonQuery();
string zapytanie = #"insert into " + #pelna_sciezka + #" (rk, Na,Ks) values (0,'" + na + "','" + ks2 +"')";
ocmd.CommandText = zapytanie;
ocmd.ExecuteNonQuery();
oconn.Close();
It's working well without any problems. But the dbf file which I using is using by another program. Why if I execute query and close connection the dbf file is still holding by program? If someone want to open it, the error message is 'file access denied'. Only if I close application, the another can get access
You are not closing your OleDbCommands. Contrary to SqlCommands, where this is de facto optional, this does make a difference for OleDb.
I recommend to use the using keyword; this ensures that all resources are released automatically at the end of the block. As an additional bonus, it ensures that the resources are also released if an exception occurs and, thus, your manual Close command would never be reached.
using (OleDbConnection oconn = new OleDbConnection()) {
oconn.ConnectionString = "Provider=vfpoledb.1;Data Source=" + pelna_sciezka + ";Collating Sequence=machine";
oconn.Open();
using (OleDbCommand ocmd = oconn.CreateCommand()) {
string na = TBNazwaKonta.Text.Replace("\n","");
na = na.Replace("\r","") ;
string ks2 = ks.Replace("\n","");
ks2 = ks2.Replace("\r", "");
using (OleDbCommand dbCmdNull = oconn.CreateCommand()) {
dbCmdNull.CommandText = "SET NULL OFF";
dbCmdNull.ExecuteNonQuery();
} // closes dbCmdNull
string zapytanie = #"insert into " + #pelna_sciezka + #" (rk, Na,Ks) values (0,'" + na + "','" + ks2 +"')";
ocmd.CommandText = zapytanie;
ocmd.ExecuteNonQuery();
} // closes ocmd
} // closes connection
I've solved my problem, there were two points that I performed:
- I've changed all ado.net code for that like Heinzi has written
- I've used the information from support.microsoft.com/kb/260856
and followed them, the problem has now disappeared. Thank you all for help!

Categories