ASP.NET CSV & ADO.NET Insert Record |
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="VB" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim objConn As New OleDbConnection
Dim objCmd As New OleDbCommand
Dim ds As New DataSet
Dim strConnString,strSQL As String
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()
With objCmd
.Connection = objConn
.CommandType = CommandType.Text
.CommandText = strSQL
End With
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()
With objCmd
.Connection = objConn
.CommandType = CommandType.Text
.CommandText = strSQL
End With
objCmd.ExecuteNonQuery()
'*** Query 2 (End) ***'
Me.lblText.Text = "Record Inserted."
objCmd = Nothing
objConn.Close()
objConn = Nothing
End Sub
</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
|