sql-server - 将 Excel 导出到 SQL 而不重复值
问题描述
我成功地在 Excel 和 SQL 之间建立了连接,并设法将 Excel 单元格中的记录添加到 SQL 数据库表中,这是我所做的教程:
我在excel中制作的(注册表单)我制作的 注册表单,我设法制作了一个宏到(注册)按钮以将数据传输到SQL数据库中,这是供参考的代码:
Sub connect()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
' Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Sheet2")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=seshbones\bones;Initial Catalog=fadi;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
Name = .Cells(iRowNo, 1)
Location = .Cells(iRowNo, 2)
Age = .Cells(iRowNo, 3)
ID = .Cells(iRowNo, 4)
Mobile = .Cells(iRowNo, 5)
Email = .Cells(iRowNo, 6)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.test (Name, Location, Age, ID, Mobile, Email) values ('" & Name & "', '" & Location & "', '" & Age & "', '" & ID & "', '" & Mobile & "', '" & Email & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
me in the table
End Sub
我想制作一个限制代码以不在表中重复相同的用户名,例如,如果客户在 excel 单元格中输入(用户名)并按下(SignUP),则必须有一个检查 SQL 数据库并检查用户名的功能已经使用并拒绝导出和消息框出现“用户已被使用”我希望你明白我的意思。
解决方案
谢谢你们的帮助,我将错误处理程序代码添加到我的项目中,所以如果我的数据库中有重复的记录,它将阻止我的程序关闭并简单地警告用户“用户名已被占用”这是我修复的方法代码 :
子连接()
Dim conn 作为新的 ADODB.Connection
将 iRowNo 变暗为整数
' 将 sCustomerId、sFirstName、sLastName 作为字符串调暗
'错误处理程序
在错误转到 ErrHandler 时:
使用工作表(“Sheet2”)
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=seshbones\bones;Initial Catalog=fadi;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
Name = .Cells(iRowNo, 1)
Location = .Cells(iRowNo, 2)
Age = .Cells(iRowNo, 3)
ID = .Cells(iRowNo, 4)
Mobile = .Cells(iRowNo, 5)
Email = .Cells(iRowNo, 6)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.test (Name, Location, Age, ID, Mobile, Email) values ('" & Name & "', '" & Location & "', '" & Age & "', '" & ID & "', '" & Mobile & "', '" & Email & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
Exit Sub
ErrHandler:MsgBox "Username Already taken" End Sub
推荐阅读
- facebook - 连接 Facebook 帐户并奖励用户的操作
- javascript - 无法检索 Javascript 变量的 API 数据
- java - 从 json 响应创建一个 java 模型
- javascript - 如何将 mongodb 的结果显示到 ejs 文件中的特定 div 中?
- php - SQLSTATE[HY000] [2002] Laravel 服务器上的连接被拒绝
- android - 如何将按钮放在回收站视图的顶部?
- terraform - 在我的本地服务器中,我丢失了 .state 文件,但 .statefile.backup 已到位。那么现在如何取回 .statefile
- jquery - 将文本框内容复制到另一个文本框,同时使用 jQuery 为每次单击字符单击键入
- postgresql - 是否有可能获得我试图在 PSQL 或 MyBatis 中复制的行的另一个字段?
- python - 如何通过命令行查找已安装的打包并与 Pycharm 一起使用