(C#) ASP.NET CSV & ADO.NET Insert Record |
(C#) ASP.NET CSV & ADO.NET Insert Record ตัวอย่างนี้จะเป็นการเขียนไฟล์ CSV โดยใช้ ADO.NET ซึ่งสามารถใช้คำสั่ง INSERT INTO เหมือนกับการ INSERT ลงใน TABLE ทั่ว ๆ ไป
Language Code : VB.NET || C#
Framework : 1,2,3,4
csv/customer.csv
CustomerID,Name,Email,CountryCode,Budget,Used
"C001","Win Weerachai","[email protected]","TH","1,000,000.00","600,000.00"
"C002","John Smith","[email protected]","EN","2,000,000.00","800,000.00"
"C003","Jame Born","[email protected]","US","3,000,000.00","600,000.00"
"C004","Chalee Angel","[email protected]","US","4,000,000.00","100,000.00"
AspNetCsvAdoInsertRecord.aspx
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb"%>
<%@ Page Language="C#" Debug="true" %>
<script runat="server">
void Page_Load(object sender,EventArgs e)
{
OleDbConnection objConn = new OleDbConnection();
OleDbCommand objCmd = new OleDbCommand();
DataSet ds = new DataSet();
String strConnString,strSQL;
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("csv/") +
";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;Format=Delimited(,)'";
objConn.ConnectionString = strConnString;
objConn.Open();
//*** Query 1 ***//
strSQL = "INSERT INTO customer.csv (CustomerID,Name,Email,CountryCode,Budget,Used) " +
"VALUES ('C005','Weerachai Nukitram','[email protected]'," +
"'TH','2,000,000.00','100,000.00')";
objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objCmd.CommandType = CommandType.Text;
objCmd.CommandText = strSQL;
objCmd.ExecuteNonQuery();
//*** Query 1 (End) ***//
//*** Query 2 ***//
strSQL = "INSERT INTO customer.csv (CustomerID,Name,Email,CountryCode,Budget,Used) " +
"VALUES ('C006','Surachai Sirisart','[email protected]'," +
"'TH','1,000,000.00','200,000.00')";
objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objCmd.CommandType = CommandType.Text;
objCmd.CommandText = strSQL;
objCmd.ExecuteNonQuery();
//*** Query 2 (End) ***//
this.lblText.Text = "Record Inserted.";
objCmd = null;
objConn.Close();
objConn = null;
}
</script>
<html>
<head>
<title>ThaiCreate.Com ASP.NET - CSV</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label id="lblText" runat="server"></asp:Label>
</form>
</body>
</html>
Screenshot
|