首页 > 代码库 > WPF基础篇----连接数据库

WPF基础篇----连接数据库

WPF连接DB2数据库
        public void ConnectionBD2Func()
        {
            //连接数据库字符串
            string strConn = "Provider=IBMDADB2;HostName=10.180.6.108;Database=workshop;port=50000;UID=eworkshop;PWD=workshop;";
            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                try
                {
                    //连接数据库
                    conn.Open();
                    //查询数据库语句
                    string commandStr = "select * from TM_EMPLOYEE";
                    //要对数据源执行的 SQL 语句或存储过程
                    OleDbCommand oleDbCmd = new OleDbCommand(commandStr, conn);
                    //表示一组数据命令和一个数据库连接,它们用于填充 System.Data.DataSet 和更新数据源。
                    OleDbDataAdapter oleDbDataAda = new OleDbDataAdapter(oleDbCmd);
                    //数据的内存中缓存
                    DataSet daSet = new DataSet();
                    //将获取到的数据填充到数据缓存中
                    oleDbDataAda.Fill(daSet);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            MessageBox.Show("Executing Finished");
        }

 

WPF连接SQLServer数据库
        public void ConnectionSQLServerFunc()
        {
            //连接数据库字符串
            string strConn = "Data Source=.;Initial Catalog=MyTest;User ID=sa;Password=password1";
            using (SqlConnection conn = new SqlConnection(strConn))
            {
                try
                {
                    //连接数据库
                    conn.Open();
                    //查询数据库语句
                    string commandStr = "select * from TM_EMPLOYEE";
                    //要对数据源执行的 SQL 语句或存储过程
                    SqlCommand sqlCmd = new SqlCommand(commandStr, conn);
                    //表示一组数据命令和一个数据库连接,它们用于填充 System.Data.DataSet 和更新数据源。
                    SqlDataAdapter sqlDataAda = new SqlDataAdapter(sqlCmd);
                    //数据的内存中缓存
                    DataSet daSet = new DataSet();
                    //将获取到的数据填充到数据缓存中
                    sqlDataAda.Fill(daSet);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            MessageBox.Show("Executing Finished");
        }

WPF基础篇----连接数据库