[英]How to insert data into SQL Server database by VB.Net in windows application
How to insert data into SQL Server database by VB.Net in Windows application. 如何在Windows应用程序中通过VB.Net将数据插入SQL Server数据库。 I am using the Windows form application. 我正在使用Windows窗体应用程序。
At run time it gives exception that: 在运行时,它给出以下异常:
con.open() the connection is not established. con.open()未建立连接。
code: 码:
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()
...
}
Where tbl1
is the table in the database. 其中tbl1
是数据库中的表。
There are typos in your connection string. 您的连接字符串中有错别字。
Security
" with " Integrated Security
". 将“ Security
”替换为“ Integrated Security
”。 Initial Catalog
". 另外,“ Initial Catalog
”中应该有一个空格。 Try this (a standard connection): 尝试以下操作(标准连接):
Password=system;Persist Security Info=True;User ID=---;Initial Catalog=shri;Data Source=.\sqlexpress
If you want your password saved in connection string for future uses of connection string of connection object set Persist Security Info=True;
如果希望将密码保存在连接字符串中,以供将来使用连接对象集的连接字符串设置,则Persist Security Info=True;
; ; other ways set it Persist Security Info=False;
其他方式将其设置为Persist Security Info=False;
Actualy when you set Persist Security Info=False;
实际上,当您将Persist Security Info=False;
设置Persist Security Info=False;
; ; The password of your connection string property of your connection object will hide. 连接对象的连接字符串属性的密码将隐藏。
Or If you use a trusted connection use this: 或者,如果您使用受信任的连接,请使用以下命令:
Integrated Security=SSPI;Initial Catalog=shri;Data Source=.\sqlexpress
Then; 然后; Change your sqlcommand
to run a stored procedure for inserting is recommended. 建议更改您的sqlcommand
以运行存储过程以进行插入。 But the better use of insert into
is this: 但是insert into
的更好用法是:
insert into <table Name> (<List of Fileds>) Values (<List of Values>)
And be careful about type of values for adding (') in your command string. 并且要注意在命令字符串中添加(')的值的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.