c data binding adds the parameter ES1en.Net to the query to connect to an external database

  • 2020-06-19 11:37:41
  • OfStack

The operation string can be defined in ACCESS database as MSSQL or as OLEDB.

MSSQL form


string sqlText = @"SELECT * FROM [User] WHERE UserName= @name";

The form of OLEDB


string sqlText = @"SELECT * FROM [User] WHERE UserName=  ? ";

The next step is to perform the operation via OleDbCommand.


OleDbCommand dataAction = new OleDbCommand(sqlText,linkDB);

The parameter assignment statement is AddWithValue:

dataAction.Parameters.AddWithValue("@name","wangyong");

The complete code is as follows:


using (OleDbConnection linkDB = new OleDbConnection(@" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\AiMeiLi.accdb"))
            {
                linkDB.Open();
                string sqlText = @"SELECT * FROM [User] WHERE UserName= @name";
                OleDbCommand dataAction = new OleDbCommand(sqlText,linkDB);
                dataAction.Parameters.AddWithValue("@name","wangyong");
                try
                {
                    OleDbDataReader scanItems = dataAction.ExecuteReader();
                    if (scanItems.HasRows)
                    {
                        while (scanItems.Read())
                        {
                            MessageBox.Show(scanItems[1].ToString());
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failure" + ex.Message);
                }
            }


Related articles: