可能写的不太清楚,以下是我的程序,有点乱,请多包涵
'scon :连接字符串, tablename:要连接的表 s:是表中的字段名
Public Function sqlinsert(ByVal scon As String, ByVal tablename As String, ByRef s() As String) As Integer
Dim con As SqlConnection = New SqlConnection '声明连接
con = sqlcon(scon)
Dim scom, sp() As String 'scom :要使用的sql语句
ReDim sp(s.Length - 2) '存放字段
scom = "insert into [" &
tablename &
"] ([" '最后是insert into [表名] ([字段1],[字段2]...) values ("@字段1","字段2"...)
Dim da As SqlDataAdapter = New SqlDataAdapter("select * from " &
tablename, con)
Dim ds As DataSet = New DataSet(tablename)
da.Fill(ds)
Dim dcs As SqlCommand = New SqlCommand("select * from " &
tablename, con)
Dim dr As SqlDataReader
con.Open()
dr = dcs.ExecuteReader()
Dim i, j As Integer
i = dr.FieldCount
For j = 0 To i - 1
sp(j) = dr.GetName(j) '取出字段
Next
'完成insert语句
For j = 0 To i - 2
scom &= sp(j) &
"] ,["
Next
scom &= sp(i - 1) &
"]) VALUES ("
For j = 0 To i - 2
scom &= "@" &
sp(j) &
", "
Next
scom &= "@" &
sp(i - 1) &
")"
Dim dc As SqlCommand = New SqlCommand(scom, con)
Dim dp(i) As SqlParameter
For j = 0 To i - 1
dp(j) = New SqlParameter
dp(j).ParameterName = "@" &
sp(j)
dp(j).Value = s(j)
'这里要给个类型,前面是动态的取出字段,这里我也想动态设置类型,请帮忙解决
dp(j).DbType=?
dc.Parameters.Add(dp(j))
Next
dr.Close()
con.Close()
con.Open()
Dim n As Integer = 0
Try
n = dc.ExecuteNonQuery()
Finally
con.Close()
End Try
Return n
End Function