.net初学者,关于动态设置数据库字段类型的问题,请大侠指点(200分)

  • 主题发起人 主题发起人 dzchen
  • 开始时间 开始时间
D

dzchen

Unregistered / Unconfirmed
GUEST, unregistred user!
我在写一个Insert函数,目的是向数据库中插入数据,我用sqlcommand和sqlparameter,在设置parameter的类型时,我想用sqldatareader将先将数据库类型读出来,然后再将它设置到parameter.dbtype里,但它的类型与sqlparameter.dbtype的类型不一样,我该怎么办,救救我吧
 
可能写的不太清楚,以下是我的程序,有点乱,请多包涵
'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
 
程序经朋友指正我做了 一点修改,不过还有一点小问题。
路过的大虾不妨试试,帮忙改改。
Public Function sqlins(ByVal con As SqlConnection, ByVal tb As String, ByVal s() As Object) As Integer 's()是传入的要插入的值
Dim scom As String = "insert into " &
tb &
" values ("
Dim sf() As String = sqlread(con, tb)
Dim i As Integer = sf.Length - 1
Dim j As Integer
For j = 0 To i - 1
scom &= """@" &
sf(j) &
""","
Next
scom &= """@" &
sf(i) &
""")"
Dim dc As SqlCommand = New SqlCommand(scom, con)
For j = 0 To i
dc.Parameters.Add("""@" &
sf(j) &
"""", s(j))
Next
con.Open()
dc.ExecuteNonQuery()
Dim n As Integer = 0
con.Close()
Return n
End Function
 
后退
顶部