繁体   English   中英

如何在Windows应用程序中通过VB.Net将数据插入SQL Server数据库

[英]How to insert data into SQL Server database by VB.Net in windows application

如何在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是数据库中的表。

您的连接字符串中有错别字。

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

您忘记为此行使用“&&”

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

或使用此链接

尝试以下操作(标准连接):

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;设置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>)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM