C#Winform gets data from the page and passes it into the database

environment:

1. Create a new data table in the SQLite database and set the corresponding fields. (Other database forms are similar, just use the package of the corresponding database)

2. The page has two textBoxes: textBox1, textBox2,

3. A save button: click the save button and it will be saved to the database

accomplish:

Pass the data obtained from the page to the database

1. Create a new class DBDao.cs, which encapsulates the method of connecting to the database ExecuteSql()

public static int ExecuteSql(string sql, params SQLiteParameter[] parameters)
        {

            using (SQLiteConnection con = new SQLiteConnection(Constants.DATA_SOURCE))
            {
                con.Open();
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteNonQuery();
                }
            }
            
        }

2. Enter data in the two text boxes on the page, and click the Save button.

private void button1_Click(object sender, EventArgs e)
        {
            string id= textBox1.Text;
            string name= textBox2.Text;
            string sql = @"insert into test(id,name) values (@id,@name)";
            DBDao.ExecuteSql(sql, new SQLiteParameter("@id", id), new SQLiteParameter("@name", name));

        }

OK

3. Others

1. C# generates a unique ID and saves it to the database

Directly use the Guid() function provided by .NET Framework:

Guid.NewGuid() refers to the rules for generating unique codes

System.Guid.NewGuid().ToString() Globally Unique Identifier (GUID) is an alphanumeric identifier

System.Guid.NewGuid().ToString(format): The format of the generated ID value:

Specifier Format of the returned value  
 
N 32 digits:  

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  
 
D 32 digits separated by hyphens:  

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  
 
B 32 digits enclosed in braces and separated by hyphens:  

{xxxxxxxx-xxxxxx -xxxx-xxxx-xxxxxxxxxxxx}  
 
P 32-digit numbers enclosed in parentheses and separated by hyphens:  

(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)  

Guid guid = Guid.NewGuid();
string id = guid.ToString("N");

After saving to the database, it is a string of 32 characters

2. Get dateTimePicker1 date:

DateTime date = dateTimePicker1.Value;
string yxq = date.ToString("yyyy-MM-dd");

The date is formatted as: "Year-Month-Day"

Guess you like

Origin blog.csdn.net/zxj19880502/article/details/129179705