有没有办法在这行代码中添加一个SQL Where子句?
抱歉,应该在这个问题上加入更多细节。这行代码连接到SQL数据库并将select语句导出到csv文件。如果我像在SQL查询中通常那样放入where子句,它会给出错误,在查询表达式中的运算符without()'ID ='1'IN''{ODBC:Driver = {SQL Server Native Client 10.0 }。
dpConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ExportDir & ";" & _
"Extended Properties=""Text;HDR=YES;"""
Dim dpTextConnection As New System.Data.OleDb.OleDbConnection(dpConnectionString)
dpTextConnection.Open()
Try
Dim dpTextCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO ["test.txt"] FROM [csv_SavedCalData] WHERE ID = '1' IN '' [ODBC;Driver={SQL Server Native Client 10.0};Server=" & sqlServer & ";Database=" & sqlDatabase & ";UID=" & sqlUN & ";PWD=" & sqlPWD & ";Trusted_Connection=yes;]", dpTextConnection)
dpTextCommand.CommandType = CommandType.Text
dpTextCommand.ExecuteNonQuery()
dpTextCommand.Dispose()
dpTextConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
答案 0 :(得分:0)
您包含它的方式与在字符串中包含SELECT和FROM子句...的方式相同,位于正确的位置
语法示例:(来自w3schools)
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
代码示例:
"SELECT * INTO [" & certExportFile & "] FROM [csv_SavedCalData] WHERE [ColumnName] IN ''
而且,正如Plutonix所说,那是一团糟。我建议reading up on SQL parameters in VB.NET
答案 1 :(得分:0)
说SQL并拥有“SQL Server Native Client 11.0”,我假设您的问题是将SQL Server表的内容导出到CSV文件。您的代码不起作用,您无法从SQL服务器表中选择文本文件。有很多方法可以解决VB.Net中的问题。一种简单的方法是从codeplex使用Linq到CSV。或者对于简单的模式,您可以直接使用文件写入功能。即:使用Northwind示例数据库,从Customers表输出一些字段:
Sub Main
Using con = New SqlConnection("server=.\SQLexpress;trusted_connection=yes;database=Northwind")
Using cmd = New SqlCommand("Select CustomerID,CompanyName,ContactName,ContactTitle,Phone,Fax,Address,City,PostalCode,Region,Country from Customers", con)
Using sw = New StreamWriter("c:\Temp\MyCustomerData.csv", False, Encoding.Default)
sw.WriteLine("CustomerID,CompanyName,ContactName,ContactTitle,Phone,Fax,Address,City,PostalCode,Region,Country")
con.Open()
Dim rdr = cmd.ExecuteReader()
While rdr.Read()
sw.WriteLine("""{0}"",""{1}"",""{2}"",""{3}"",""{4}"",""{5}"",""{6}"",""{7}"",""{8}"",""{9}"",""{10}""", _
rdr("CustomerID"), rdr("CompanyName"), rdr("ContactName"), rdr("ContactTitle"), rdr("Phone"), _
rdr("Fax"), rdr("Address"), rdr("City"), rdr("PostalCode"), rdr("Region"), rdr("Country"))
End While
End Using
End Using
End Using
End Sub