I have attached my code in which I tried to read a .txt file with many records.
The same text file data I need to insert into the SQL Server database table in specific columns. Here is the code I wrote by taking reference from some where.
protected void BtnUpload_Click(object sender, EventArgs e)
{
FileUpload(x);
}
private void FileUpload(List<string> x)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand();
string fileName = Path.Combine(#"C:\Users\user\Desktop\SBS", FileUpload1.FileName);
if(FileUpload1.HasFile)
{
try
{
con.Open();
List<string> x;
for (int i = 0; i <= x.Count - 9; i += 9)
{
SqlCommand myCommand = new SqlCommand("INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) " +
string.Format("Values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}')", x[i], x[i + 1], x[i + 2], x[i + 3], x[i + 4], x[i + 5], x[i + 6], x[i + 7], x[i + 8], x[i + 9]), con);
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
}
example of my file :
1 |abc| |bcd| |101|
here | denoted separator of column and yes every line should be inserted in the table where in specific column is available
Can anyone help me to insert file data into the SQL Server table?
Please help me to solve the issue
I wouldn't use a program at all... I'd use the "Import" feature in SQL server to import a pipe-delimited file. For example How to import pipe delimited text file data to SQLServer table
Here is an example of working code that will read data from a Text file, where that data is delimited by |. Multiple insert statements will be executed within a single transaction, in case of failure using an All Or Nothing principle.
[TestMethod]
public void TestInsertDataFromFile()
{
String fileName = #"D:\SampleData.txt";
String connectionString = #"Server=MyTestDBServer; Database=TestingDatabase; Trusted_Connection=True;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction transaction = conn.BeginTransaction())
{
String insertCommand = #"INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) ";
insertCommand += #"VALUES (#sbsBranchCode, #branchName, #finYear, #brChallanNo, #transDate, #majorHead, #receiptPayment, #amount, #planNonPlan)";
String[] fileContent = File.ReadAllLines(fileName);
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = insertCommand;
command.CommandType = CommandType.Text;
command.Transaction = transaction;
foreach (String dataLine in fileContent)
{
String[] columns = dataLine.Split('|');
command.Parameters.Clear();
command.Parameters.Add("sbsBranchCode", SqlDbType.VarChar).Value = columns[0];
command.Parameters.Add("branchName", SqlDbType.VarChar).Value = columns[1];
command.Parameters.Add("finYear", SqlDbType.VarChar).Value = columns[2];
command.Parameters.Add("brChallanNo", SqlDbType.VarChar).Value = columns[3];
command.Parameters.Add("transDate", SqlDbType.VarChar).Value = columns[4];
command.Parameters.Add("majorHead", SqlDbType.VarChar).Value = columns[5];
command.Parameters.Add("receiptPayment", SqlDbType.VarChar).Value = columns[6];
command.Parameters.Add("amount", SqlDbType.VarChar).Value = columns[7];
command.Parameters.Add("planNonPlan", SqlDbType.VarChar).Value = columns[8];
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
}
}
Important things to note
NEVER have an empty catch {} handler as you will never know if there are problems.
When talking to the database using externally specified values, ALWAYS use parameters to prevent SQL Injection attacks.
Make use of Transactions if you are doing multiple inserts from a single source. It will make recovery possible without having to unpick the data manually.
Where possible (when classes implement IDisposable) use a using(...) block to ensure resources are released and not blocking/locking.
use this code:
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand();
string fileName = Path.Combine(#"C:\Users\user\Desktop\SBS", FileUpload1.FileName);
if (FileUpload1.HasFile)
{
var lines = File.ReadAllLines(fileName);
try
{
con.Open();
foreach (var line in lines)
{
var columns = line.Split('|');
SqlCommand myCommand = new SqlCommand("INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) " +
$"Values('{columns[0]}', '{columns[1]}','{columns[2]}','{columns[3]}','{columns[4]}','{columns[5]}','{columns[6]}','{columns[7]}','{columns[8]}''{columns[9]}')");
myCommand.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
}
}
Related
I have my sqlite database stored in C:\program-name\db\db.s3db.
I have a table members with about 70 records. So now there is a procedure that i have to do, which is copying all account numbers from the members table to the other table act_monthly_listings.
Its showing that it's executing but it's excrutiatingly slow. I don't know if it is because of my code. Here is a snippet:
Connection:
private void SetConnection()
{
sql_con = new SQLiteConnection
("Data Source=C:\\credit-union\\db\\cu.s3db;Version=3;New=False;Compress=True;");
}
On ButtonClick Code:
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Working Please Wait";
string init_month = dtInit.Value.Month.ToString();
string init_yr = dtInit.Value.Month.ToString();
SetConnection();
sql_con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = "select ec_no from members";
cmd.Connection = sql_con;
DR = cmd.ExecuteReader();
int count = 0;
while (DR.Read())
{
DR.Read();
this.Text = "Account : " + DR.GetInt32(0).ToString();
string SQL = "INSERT INTO act_monthly_listings (year,month,act) VALUES ("+ init_yr + "," + init_month + "," + DR.GetInt32(0).ToString() + ")";
//Clipboard.SetText(SQL)
if (ExecuteQuery(SQL))
{
count++;
}
}
if(count > 0){
MessageBox.Show("Accounts Initialized!", "Success", MessageBoxButtons.OK,MessageBoxIcon.Information);
}else{
MessageBox.Show("Initialization Failed!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
sql_con.Close();
}
That is because of while you are executing insert query equal to row count which make your program run very slow so this is better to use
INSERT INTO-SELECT like:
string init_month = dtInit.Value.Month.ToString();
string init_yr = dtInit.Value.Month.ToString();
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = "INSERT INTO act_monthly_listings (year,month,act) select #y,#m,ec_no from members";
cmd.Parameters.Add(new SQLiteParameter("#y", init_yr ));
cmd.Parameters.Add(new SQLiteParameter("#m", init_month ));
cmd.Connection = sql_con;
cmd.ExecuteNonQuery();
all the rows inserted in one shoot, while you are using while until reader.Read() pointer arrived to last row the DataReader is connecting with DB (Need to alive connection) that may make connection pooling slow plus you are executing a query per Read avoid this,
suppose you have a million record then what happened by your code?
I am currently writing a piece of code where the user is supposed to insert a few information about an employee and press one button populate for populating a gridview and another one to save the information in gridview into a local database. While running the what I wrote so far there is a consistent error saying "SqlExeption was unhandled by the user code. I have been trying to fix it but without success. It complains on conn.Open();
This is that specific piece of code:
protected void SaveButton_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(#"Data Source = C:\EmployeeWebProject\EmployeeWebProject\App_Data\EmployeeDatabase.sdf"))
{
using (SqlCommand comm = new SqlCommand("SELECT * FROM Employee"))
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO Employee VALUES ("
+ GridView1.Rows[i].Cells[0].ToString() + ", "
+ GridView1.Rows[i].Cells[1].ToString() + ", "
+ GridView1.Rows[i].Cells[2].ToString() + ", "
+ GridView1.Rows[i].Cells[3].ToString() + ", "
+ GridView1.Rows[i].Cells[4].ToString() + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
finally
{
}
}
To avoid SQL injection and use properly parametrized queries, and also use the SQL Server CE connection and command objects, try this code:
protected void SaveButton_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
// define connection string and INSERT query WITH PARAMETERS
string connectionString = #"Data Source = C:\EmployeeWebProject\EmployeeWebProject\App_Data\EmployeeDatabase.sdf";
string insertQry = "INSERT INTO Employees(Col1, Col2, Col3, Col4, Col5) " +
"VALUES(#Col1, #Col2, #Col3, #Col4, #Col5);";
// define connection and command for SQL Server CE
using (SqlCeConnection conn = new SqlCeConnection(connectionString))
using (SqlCeCommand cmd = new SqlCeCommand(insertQry, conn))
{
// add parameters to your command - adapt those *as needed* - we don't know your table structure,
// nor what datatype (and possibly length) those parameters are !
cmd.Parameters.Add("#Col1", SqlDbType.Int);
cmd.Parameters.Add("#Col2", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#Col3", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#Col4", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#Col5", SqlDbType.VarChar, 100);
conn.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
// set parameter values
cmd.Parameters["#Col1"].Value = Convert.ToInt32(GridView1.Rows[i].Cells[0]);
cmd.Parameters["#Col2"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["#Col3"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["#Col4"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["#Col5"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.ExecuteNonQuery();
}
}
}
finally
{
}
}
I am trying to add records into my C# project and it runs with no errors but it doesn't add anything in the database:
private void saveBtn_Click(object sender, EventArgs e)
{
if (admNo.Text != "" & session.Text != "" & name.Text != "")
{
SqlConnection cn = new SqlConnection("Data Source=C:\\Users\\Divya Pathak\\Documents\\Visual Studio 2012\\Projects\\SchoolRecord\\SchoolRecord\\Database1.sdf");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into addNew (no,session,name) values ('" + admNo.Text + "', '" + session.Text + "', '" + name.Text + "')";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record inserted successfully", "mission successfull");
}
}
Could someone please advise why?
you need to set cm.Connection as cn
cm.Connection =cn;
OR
using (var cn = new SqlCeConnection("connection string"))
using (var cmd = new SqlCeCommand("insert addNew (no,session,name) values (#no,#session,#name)", cn))
{
cmd.Parameters.AddWithValue("#no", admNo.Text);
cmd.Parameters.AddWithValue("#session", session.Text);
cmd.Parameters.AddWithValue("#name", name.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
This will help you to write the correct connection string for SQL CE
You have four mistakes:
You never associate the connection with the command
You're connecting to a Sql Server Compact database using the full Sql Server provider (you should be using the SqlCe namespace:
You're building your query using unsafe string concatenation instead of query parameters. Fix this!
Your connection won't be closed if an exception is thrown, which can ultimately lock you out of your database. You need to close the connection as part of a finally block, and the easiest way to do this is with a using block.
.
using (var cn = new SqlCeConnection("connection string here"))
using (var cmd = new SqlCeCommand("insert into addNew (no,session,name) values (#no,#session,#name)", cn))
{
//guessing at column lengths:
cmd.Parameters.Add("#no", SqlDbType.Int).Value = int.Parse(admNo.Text);
cmd.Parameters.Add("#session", SqlDbType.NVarChar, 100).Value = session.Text;
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 60).Value = name.Text;
cn.Open();
cmd.ExecuteNonQuery();
}
i have this code for insert data into access 2013
after click in the save button data insert into dataGridView and show
and when stop program and restart this,data not stored in the DB.I've done a lot of searches but can't find the solution. my class code and my button save code
class DB
{
public static OleDbConnection con = new OleDbConnection();
static DB()
{
con.ConnectionString = "Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;Persist Security Info=True";
}
public static void Insert(Person p1)
{
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES('" + p1.Name + "','" + p1.Family + "','" + p1.Telephone + "','" + p1.Major + "')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = s;
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
}
}
Person p = new Person();
p.Name = txtname.Text;
p.Family = txtfamily.Text;
p.Telephone = txttell.Text;
p.Major = txtmajor.Text;
DB.Insert(p);
txttell.Text = "";
txtmajor.Text = "";
txtname.Text = "";
txtfamily.Text = "";
List<Person> people = DB.GetPeople();
dataGridView1.DataSource = people;
Choose your ACCDB file listed in your project files, select Copy To Output Directory and set its value to Never (And remember that |DataDirectory| is a substitution strings that points (for ASP.NET projects) to APP_DATA, your record is inserted in the database copied in that directory.
Said that please consider to use a parameterized query to create an sql command, not string concatenations
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES(" +
"?,?,?,?)";
cmd.CommandText = s;
cmd.Parameters.AddWithValue("#p1",p.Name);
cmd.Parameters.AddWithValue("#p2",p.Family);
cmd.Parameters.AddWithValue("#p3",p.Telephone);
cmd.Parameters.AddWithValue("#p4",p.Major);
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
Of course do not close the connection before executing the command.
Another point to change is the usage pattern of your connection. Do not create a global connection and keep it around for the lifetime of your application. Simply create and use it when needed and close/dispose immediately after
using(OleDbConnection con = new OleDbConnection("Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;" +
"Persist Security Info=True"))
{
try
{
OleDbCommand cmd = con.CreateCommand();
....
}
} // <- Here at the closing brace the connectio will be close and disposed
Iam fairly new to SQLClient and all, and iam having a problem with my SQL tables..when ever i run my code, the data, rather than getting updated, attaches itself to the already existing records in the tables..here's my code
SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
cmd.ExecuteNonQuery();
}
conneciones.Dispose();
Take a look at these functions, i hope you understand better on update , insert and delete functions..
Code snippets for reading, inserting, updating and deleting a records using asp.net and c# and sql server database
static void Read()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Id = ", reader["Id"]);
Console.WriteLine("Name = ", reader["Name"]);
Console.WriteLine("Address = ", reader["Address"]);
}
}
reader.Close();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Update()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE EmployeeDetails SET Name=#NewName, Address=#NewAddress WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Munna Hussain");
cmd.Parameters.AddWithValue("#Address", "Kerala");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Delete()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("DELETE FROM EmployeeDetails " +
"WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
int rows = cmd.ExecuteNonQuery();
//rows number of record got deleted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
Your code should be inserting new records, but I'm not clear on whether it is not doing that, or you mean to update existing records.
Aside from that, understanding that you are new to working with SQL Server, there are a couple of things you should be aware of.
You should use using to automatically dispose resources. This will also close your connection for you so you don't have open connections hanging around.
You should use parameters to protect against sql injection attacks. Another benefit of using parameters in your case is that you don't need to create new commands for every statement.
For example:
using (var connection = new SqlConnection(connectionString)
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into URL_Entries values(#url, #now, #leak)";
command.Parameters.AddWithValue("#now", DateTime.Now);
command.Parameters.AddWithValue("#lead", leak);
// update to correspond to your definition of the table column
var urlParameter = command.Parameters.Add(new SqlParameter("#url", SqlDbType.VarChar, 100));
connection.Open();
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
urlParameter.Value = CleanedURLlist[ok];
command.ExecuteNonQuery();
}
}
Per your comment, if you want to do an update, you'll need to include the parameter(s) that identify the rows to update. If this is a single row, use the primary key value:
command.CommandText = "update URL_Entries set UrlColumn = #url, ModifiedDate = #now where ID = #id";
You're using an INSERT function, that is 'ADD NEW RECORDS'
If you want an update, you'll want an UPDATE function
UPDATE tablename
SET column1 = 'x', column2 = 'y'
WHERE id = z