【问题标题】:How to insert data into SQL Server database by VB.Net in windows application如何在 Windows 应用程序中通过 VB.Net 将数据插入 SQL Server 数据库
【发布时间】:2015-03-08 05:09:11
【问题描述】:

如何在 Windows 应用程序中通过 VB.Net 将数据插入 SQL Server 数据库。我正在使用 Windows 表单应用程序。
在运行时,它会给出以下异常:

con.open() 连接未建立。

代码:

imports system.data
imports system.data.sqlclient

on button_click(){

    Dim cn as SqlConnection=new SqlConnection("Data Source=.\sqlexpress;InitialCatlog=shri;Security=True;User id=---;password=system")
    cn.close()
    cn.Open()
    Dim cmd as SqlCommand=new SqlCommand("insert into tbl1 values('"&textbox1.Text&"','"textbox2.Text"')",cn)
    cmd.executeNonQuery()
    messageBox.Text="record Inserted"
    cn.close()
    ...
}

其中tbl1 是数据库中的表。

【问题讨论】:

  • 你使用trusted connection吗?

标签: c# php vb.net connection-string


【解决方案1】:

您的连接字符串中有拼写错误。

  • 将“Security”替换为“Integrated Security”。
  • 另外,“Initial Catalog”中应该有一个空格。

【讨论】:

  • 但如果它在运行时显示异常,则连接未建立,我该怎么办?
【解决方案2】:

试试这个(标准连接):

Password=system;Persist Security Info=True;User ID=---;Initial Catalog=shri;Data Source=.\sqlexpress

如果您希望将密码保存在连接字符串中以供将来使用连接对象集Persist Security Info=True;的连接字符串;其他方式设置Persist Security Info=False;

实际上当你设置Persist Security Info=False;;连接对象的连接字符串属性的密码将隐藏。

或者,如果您使用受信任的连接,请使用:

Integrated Security=SSPI;Initial Catalog=shri;Data Source=.\sqlexpress

然后;建议更改您的 sqlcommand 以运行用于插入的存储过程。但是insert into更好的用法是这样的:

insert into <table Name> (<List of Fileds>) Values (<List of Values>)

并注意在命令字符串中添加 (') 的值类型。

【讨论】:

  • 我不知道 sql server 的密码,那么我应该在连接字符串中写什么。
  • 我不知道 sql server 的密码,那么我应该在连接字符串中写什么。而且在复制字符串的情况下,sring Pooling=false 中有一个属性是否我应该留不留
  • 好的!所以您使用了受信任的连接(使用 Windows 进行身份验证),所以我编辑了我的答案。使用这个link
【解决方案3】:

你忘记在这一行使用 '& &'

Dim cmd as SqlCommand=new SqlCommand("insert into tbl1 values('"& textbox1.Text &"','"& textbox2.Text &"')",cn)

或使用此link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多