Add data to the database (SQL Server)

Source: Internet
Author: User

 

Use the CommandText method of the SqlCommand class (to construct an insert statement for it) and ExecuteNonQuery to insert data into the table. The main program code is as follows. First, instantiate a SqlCommand object (cmd), and then use the SQL parameter (SQL statement) to create a cmd object. Finally, run the SQL statement using the ExecuteNonQuery METHOD OF THE cmd object.

Public bool insertDB (String SQL)
{
Using (SqlCommand cmd = new SqlCommand ())
{
Try
{
Cmd. CommandText = SQL; // set the SQL statement
Cmd. Connection = ConDB (); // call the method for opening the database Connection
Cmd. ExecuteNonQuery (); // Execute
Return true;
}
Catch
{
Return false;
}
}
} Click the "add information" button to create an SQL statement ). Then, the statement is passed to the insertDB method to add data.

Private void button#click (object sender, EventArgs e)
{
ClsDB. ClsDBControl DBC = new OptDB. ClsDB. ClsDBControl ();
String strSql = "insert into t_people values (" + this. textBox1.Text. Trim (). ToString () + "," +
This. textBox2.Text. Trim (). ToString () + "," + this. textBox3.Text. Trim (). ToString () + ")";
If (DBC. insertDB (strSql ))
{
MessageBox. Show ("OK ");
}
} NOTE: When adding information, the SQL reference variable format is "+ variable +"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.