C#鏈接SQLServer實現插入和查詢數據源代碼

數據的查詢:
private void FullTab() {
        SqlConnection con1 = new SqlConnection();//創建數據庫庫鏈接
            try
            {
                String con = "server=.;database=common_wjdl;uid=sa;pwd=db2008mima";//定義數據庫連接信息
                con1.ConnectionString = con;
                con1.Open();//打開數據庫
                String sql = "select * from Fileuploaded";//創建語句查詢所有數據
                SqlDataAdapter ada1 = new SqlDataAdapter(sql, con);//SqlDataAdapter 對象。 用於填充DataSet (數據集)。
                DataSet myset = new DataSet();
                SqlCommand cmd = con1.CreateCommand();//創建數據庫命令
                cmd.CommandText = sql;
                SqlDataReader reader = cmd.ExecuteReader(); //從數據庫中讀取數據流存入reader中
            }
            catch (SqlException ee1)
            {
                Console.WriteLine(ee1.Message);//打印異常信息
            }
            catch (IndexOutOfRangeException ee2) {
                Console.WriteLine(ee2.Message);//打印異常信息
            }
        }
        
數據的插入:(大致都一樣,只需修改SQL語句就行)
            String con = "server=.;database=common_wjdl;uid=sa;pwd=db2008mima";//定義數據庫連接信息
                            con1.ConnectionString = con;
                            con1.Open();//打開數據庫
                            String sql = "insert into Fileuploaded (FileID,FileName,FilePath,QRCodePath,FileSuffix) Values('"+fileNameSave+"','"+fileName+"','"+filePath+"','"+filePath+"','"+fileSuffix+"')";//創建語句向數據庫插入數據
                            SqlCommand cmd = con1.CreateCommand();//創建數據庫命令
                            cmd.CommandText = sql;
                            cmd.ExecuteNonQuery();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章