C#:SqlServer操作的知识点
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);
}
}
C#:SqlServer操作的知识点的更多相关文章
- SqlServer 操作 JSON
SqlServer 操作 JSON Intro Sql Server 从 2016 开始支持了一些 json 操作,最近的项目里也是好多地方直接用字段直接存成了 json ,需要了解一下怎么在 Sql ...
- SqlServer操作大全
一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备份数 ...
- android使用xfire webservice框架远程对sqlserver操作(包括增删改查)的实例!!已在真机上试验通过
前两天,公司有一个利用android远程操作sqlserver的项目,对此我是毫无头绪的,但也挺感兴趣的,于是开始上网搜索方法,网上有挺多方法了,发现使用webservice的挺多的,不过我对这些技术 ...
- C#操作Excel知识点
近期在使用C#操作excel,主要是读取excel模板,复制其中的模板sheet页,生成多个sheet页填充相应数据后另存到excel文件,所用到的知识点如下. 一.添加引用和命名空间 添加Micro ...
- C# 操作office知识点汇总
1. C#操作Word的超详细总结
- python基础之列表常用操作及知识点小结
列表(list) List(列表) 是 Python 中使用最频繁的数据类型.列表可以完成大多数集合类的数据结构实现.它支持字符,数字,字符串甚至可以包含列表(所谓嵌套).列表用[ ]标识,是pyth ...
- sqlserver 操作xml
1.xml.exist 输入为XQuery表达式,返回0,1或是Null.0表示不存在,1表示存在,Null表示输入为空 2.xml.value 输入为XQuery表达式,返回一个SQL ...
- MS SQLServer 操作XML语句的存储过程
-- ================================================ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ...
- SQLServer操作结果集
union组合结果集 --相同合并 union --全部显示 union all 公用表表达式 with CET( wName,dName) as ( select wName,dName from ...
随机推荐
- The method setClass(Context, Class<?>) in the type Intent is not applicable for the arguments (GameV
在当前短信内容的activity中写 Bundle bun = new Bundle(); bun.putString("message", ...
- 在iOS 7中使用storyboard(part 1)
原文:Storyboards Tutorial in iOS 7: Part 1 感谢翻译小组成员heartasice热心翻译.如果您有不错的原创或译文,欢迎提交给我们,更欢迎其他朋友加 ...
- 解决Visual Studio 2015创建工程时的“DNX SDK version 'dnx-clr-win-x86.1.0.0-beta5' failed to install.”错误
前段时间发布了Visual Studio2015,在后,发现创建Asp.Net工程和时,出现了"DNX SDK version 'dnx-clr-win-x86.1.0.0-beta5' f ...
- HDU 4611 Balls Rearrangement(2013多校2 1001题)
Balls Rearrangement Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Othe ...
- 降压转换器 (Buck)
降压转换器 (Buck) 切换式降压转换器 (Buck) 能提供高效率.高度弹性.高压降比.高负载能力的降压转换. 多数降压转换器 (Buck) 包含上桥 MOSFET 和同步整流 MOSFET,根据 ...
- Using an open debug interconnect model to simplify embedded systems design
Using an open debug interconnect model to simplify embedded systems design Tom Cunningham, Freescale ...
- Papilio Pro Boards
http://papilio.cc/index.php?n=Papilio.PapilioOne The Papilio is an Open Source FPGA development boar ...
- [Linux] Ubuntu下解压rar文件的方法
一般通过默认安装的ubuntu是不能解压rar文件的,只有在安装了rar解压工具之后,才可以解压.其实在ubuntu下安装rar解压工具是非常简单的,只需要两个步骤就可以迅速搞定. ubuntu 下r ...
- go语言基础之递归实现数字累加
1.实现1+100 = 5050 示例: package main import "fmt" //实现1+2+3+……100 func test01() (sum int) { f ...
- Sn.exe(强名称工具)
Sn.exe(强名称工具) .NET Framework 4.5 强名称工具 (Sn.exe) 有助于使用强名称对程序集进行签名. Sn.exe 提供了用于密钥管理.签名生成和签名验证的选项. 强 ...