Vb.net利用数据工厂建立(DBMS)数据操作模型

前端之家收集整理的这篇文章主要介绍了Vb.net利用数据工厂建立(DBMS)数据操作模型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Imports System.Configuration
Imports System.Data.Common

'还需要引用system.configuration
app.config中配置连接字符串
<configuration>
<connectionStrings>

<add name="数据工厂测试.My.MySettings.Setting" connectionString="Data Source=wangli;Initial Catalog=VideoGames;Persist Security Info=True;User ID=sa;Password=sa"
providerName="System.Data.sqlClient" />
<add name ="VideoGameStoreDb" connectionString ="Data Source=wangli;Initial Catalog=VideoGames;Persist Security Info=True;User ID=sa;Password=sa"
providerName="System.Data.sqlClient"/>
</connectionStrings>
</configuration>

  1. Public Class ClsFactory
  2. Public Sub Delete(ByVal pId As Integer)
  3. '获得连接字符串
  4. Dim css As ConnectionStringSettings
  5. css = ConfigurationManager.ConnectionStrings("VideoGameStoreDb")
  6.  
  7. '在数据连接的上建立工厂类
  8. Dim Factory As DbProviderFactory
  9. Factory = DbProviderFactories.GetFactory(css.ProviderName)
  10.  
  11. '建立连接 ,执行任务
  12. Using conn As DbConnection = Factory.CreateConnection
  13. conn.ConnectionString = css.ConnectionString
  14.  
  15. '生成命令
  16. Using cmd As DbCommand = Factory.CreateCommand
  17. cmd.Connection = conn
  18. cmd.CommandType = CommandType.Text
  19. cmd.CommandText = "delete from customer where customerId=@id"
  20.  
  21. '创建ID参数
  22. Dim paramID As DbParameter
  23. paramID = Factory.CreateParameter
  24. paramID.ParameterName = "@id"
  25. paramID.Value = pId
  26.  
  27. cmd.Parameters.Add(paramID)
  28.  
  29. '打开连接,执行
  30. conn.Open()
  31. Dim count As Integer
  32. count = cmd.ExecuteNonQuery
  33.  
  34. conn.Close()
  35.  
  36. If count < 1 Then
  37. Throw New ArgumentOutOfRangeException("id","序号没有找到")
  38. End If
  39.  
  40. End Using
  41. End Using
  42. End Sub
  43. End Class


'为了降低sql注入攻击的威胁(sql injection),建议使用参数,而不要使用字符串的连接。恶意sql代码可能通过字符串的连接而执行。如:操作者可能在某一字段 输入一个右引号,后面跟完整sql语句。由于该字符串会被追加到SELECT 语句的后面,引事情后的语句便会执行。

猜你在找的VB相关文章