简体   繁体   中英

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. I am using the Windows form application.
At run time it gives exception that:

con.open() the connection is not established.

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.

There are typos in your connection string.

  • Replace " Security " with " Integrated Security ".
  • Also, there should be a space in " Initial Catalog ".

you forgot using of '& &' for this line

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

or use this link

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; ; other ways set it Persist Security Info=False;

Actualy when you set 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. But the better use of insert into is this:

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

And be careful about type of values for adding (') in your command string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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