1、检查数据库连接的有效性 var client = new System.Net.Sockets.TcpClient(); var ar = client.BeginConnect(host, 1433, null, null); ar.AsyncWaitHandle.WaitOne(500); return client.Connected; client.Close(); 2、检查连接字符串是否可以连接数据库 SqlConnection _connection; if (_connection == null) { _connection = new SqlConnection(ConnectionString); _connection.Open(); } else if (_connection.State == System.Data.ConnectionState.Closed) { _connection.Open(); } else if (_connection.State == System.Data.ConnectionState.Broken) { _connection.Close(); _connection.Open(); } return _connection; 3、判断是否存在某表的某个字段 string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; using (SqlCommand cmd = new SqlCommand(sql , Connection)) { object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } Connection.Close(); 4、执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) SqlCommand cmd = new SqlCommand(strSQL, Connection); SqlDataReader reader= cmd.ExecuteReader(CommandBehavior.CloseConnection); if (reader.Read()) { reader["columnName"].ToString(); } reader.Close(); Connection.Close(); 5、执行查询语句,返回DataSet DataSet ds = new DataSet(); SqlDataAdapter command = new SqlDataAdapter(SQLString, Connection); command.Fill(ds, "ds"); Connection.Close(); 6、 执行SQL语句,返回影响的记录数 SqlCommand cmd = new SqlCommand(); if (conn.State != ConnectionState.Open) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = sql; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; conn.Close(); 7、批量复制数据、插入数据,实现数据库事务 if (conn.State != ConnectionState.Open) { conn.Open(); } SqlTransaction trans = conn.BeginTransaction(); //定义批量处理对象 SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.KeepIdentity, trans); foreach (DataColumn item in dataTable.Columns) { bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName); } //指定被操作的数据表名 bulkCopy.DestinationTableName = tableName; bulkCopy.BatchSize = size; bulkCopy.BulkCopyTimeout = 50; //数据插入到数据库 bulkCopy.WriteToServer(dataTable); bulkCopy.Close(); bool isSuccess = ture; if (isSuccess) { trans.Commit(); } else { trans.Rollback(); } 8、执行存储过程 DataSet dataSet = new DataSet(); SqlDataAdapter sqlDA = new SqlDataAdapter(); SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } sqlDA.SelectCommand = command; //sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); Connection.Close(); //command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); //rowsAffected = command.ExecuteNonQuery(); //result = (int)command.Parameters["ReturnValue"].Value; 9、备份数据库 SqlCommand command = new SqlCommand("use master;backup database @name to disk=@path;", Connection); command.Parameters.AddWithValue("@name", dbName); command.Parameters.AddWithValue("@path", pathDB); //command.Parameters.AddWithValue("@pathLog",pathLog); num = command.ExecuteNonQuery(); Connection.Close(); 10、恢复sql server数据库 SqlCommand command = new SqlCommand("use master;restore database @name from disk=@path WITH replace;", Connection); command.Parameters.AddWithValue("@name", dbName); command.Parameters.AddWithValue("@path", pathDB); //command.Parameters.AddWithValue("@pathLog",pathLog); num = command.ExecuteNonQuery(); Connection.Close(); 11、加载Excel string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'"; OleDbConnection OleConn = new System.Data.OleDb.OleDbConnection(strConn); OleConn.Open(); System.Data.DataTable sheetNames = OleConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });//获得Excel 表的架构信息 String sql = "SELECT * FROM [" + sheetNames.Rows[0]["TABLE_NAME"] + "]";//可是更改Sheet名称,比如sheet2,等等 OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn); DataSet OleDsExcle = new DataSet(); OleDaExcel.Fill(OleDsExcle); OleConn.Close(); return OleDsExcle;
特别操作
1、获取全部数据库名称 ArrayList DBNameList = new ArrayList(); SqlConnection Connection = new SqlConnection(String.Format("Data Source={0};Initial Catalog=master;User ID={1};PWD={2}", DSN, UID, PWD)); DataTable DBNameTable = new DataTable(); SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", Connection); Adapter.Fill(DBNameTable); foreach (DataRow Row in DBNameTable.Rows) { DBNameList.Add(Row[0]); } 2、得到指定数据库中的全部表名称 string constr = String.Format("Data Source={0};Initial Catalog={1};User ID={2};PWD={3}", DSN, dbname, UID, PWD); SqlConnection myConnection = new SqlConnection(constr); //根据选中数据库,得到相应的所有表 string strSQL = "select name from sysobjects where type='" + 'U' + "'"; DataSet ds = new DataSet(); SqlDataAdapter myCommand = new SqlDataAdapter(strSQL, myConnection); myCommand.Fill(ds, "table"); List<string> tableName = new List<string>(); DataTable dt = ds.Tables[0]; foreach (DataRow item in dt.Rows) { tableName.Add(item[0].ToString()); } 3、SQL变量 SqlCommand cmd = new SqlCommand(sql, sqlCon); SqlParameter para = new SqlParameter("@UHDATA", SqlDbType.Image); para.Value = UHDATA; //UHDATA 变量是 byte[] cmd.Parameters.Add(para);
1、更加数据库连接和sql语句获取字段值
private string GetFieldStringValue(OleDbConnection oleconn, string ASqlStr) { string strResult = string.Empty; OleDbCommand comTemp = new OleDbCommand(ASqlStr); comTemp.Connection = oleconn; OleDbDataReader readerTemp = comTemp.ExecuteReader(); if (readerTemp.HasRows) { readerTemp.Read(); strResult = readerTemp.GetString(0); } readerTemp.Close(); return strResult; }
参考:double数组转为image类型(即byte[])
public byte[] GetDoubleToByte(double[] d) { int size = Marshal.SizeOf(d[0]) * d.Length; IntPtr pnt = Marshal.AllocHGlobal(size); try { // Copy the array to unmanaged memory. Marshal.Copy(d, 0, pnt, d.Length); // Copy the unmanaged array back to another managed array. byte[] managedArray2 = new byte[d.Length * 8]; Marshal.Copy(pnt, managedArray2, 0, d.Length * 8); return managedArray2; } finally { // Free the unmanaged memory. Marshal.FreeHGlobal(pnt); } }