C# acess 数据库连接与使用示例

        private static string Database1ConnectionString = StudentManagement.Properties.Settings.Default.Database1ConnectionString;

        // 获取连接对象
        public static OleDbConnection getConn()
        {
            //创建连接对象
            OleDbConnection conn = new OleDbConnection(Database1ConnectionString);
            try
            {
                conn.Open();
            }
            catch(Exception e2)
            {
                MessageBox.Show("数据库连接错误:" + e2.Message, "错误提示");
                return null;
            }
            return conn;
        }
        // 关闭连接对象
        public static void closeConn(OleDbConnection conn)
        {
            // 关闭连接对象
            try
            {
                conn.Close();
            }
            catch
            {
                MessageBox.Show("数据库连接错误", "错误提示");
            }
        }







                    string query = "select 1 from student where sno=" + name + " and password =\"" + ps +"\"";
                    OleDbConnection conn = getConn();

/**方式1:使用OleDbCommand + ExecuteXxx */
                    // 查询用户名对应的密码
                    OleDbCommand cmd = new OleDbCommand(query, conn);
                    Object res = cmd.ExecuteScalar();
                    if (res == null || int.Parse(res.ToString()) < 1)
                    {
                        MessageBox.Show("用户名请输入正确学号");
                    }

                    // 如果有符合的记录,打开学生窗口
                    StudentForm studentf = new StudentForm(int.Parse(name));
                    studentf.Show();
                    return;

/**方式2:使用OleDbDataAdapter + DataSet */


                    OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(query, conn);

                    DataSet dataSet = new DataSet();
                    oleDbDataAdapter.Fill(dataSet);
                    if (dataSet.Tables[0].Rows.Count > 0)
                    {
                        String a = dataSet.Tables[0].Rows[0].ItemArray[0].ToString();
                        if ( "1".Equals(a))
                        {
                            // 如果有符合的记录,打开学生窗口
                            StudentForm studentf = new StudentForm(int.Parse(name));
                            studentf.Show();
                            return;
                        }
                    }
                    dataSet.Reset();    

 

posted @ 2020-12-12 20:03  原子切割员  阅读(196)  评论(0编辑  收藏  举报