天津理工大学C#期末复习总结
- 格式:docx
- 大小:27.40 KB
- 文档页数:14
C#资料
一、数据库相关
连接字符串:
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial
Catalog=myDataBase;User ID=myUsername;Password=myPassword;
string sqlConnection="DATA SOURCE=(local);DATABASE=DB;USER ID=SA;PWD=123";
public static readonly string connstr = "Data Source=vmb72;Initial Catalog=SCHOOL;Integrated Security=True;Connect Timeout=15";
"Data Source=C:\BegASPNET\Northwind.mdb"是指明数据源的位置,他的标准形式是"Data Source=MyDrive:MyPath\MyFile.MDB". PS: 1."+="后面的"@"符号是防止将后面字符串中的"\"解析为转义字符. 2.如果要连接的数据库文件和当前文件在同一个目录下,还可以使用如下的方法连接: strConnection+="Data Source=";strConnection+=MapPath("Northwind.mdb"; 这样就可以省得你写一大堆东西了!
3.要注意连接字符串中的参数之间要用分号来分隔. "OleDbConnection
objConnection=new OleDbConnection(strConnection);"这一句是利用定义好的连接字符串来建立了一个链接对象,以后对数据库的操作我们都要和这个对象打交道.
打开连接:
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
操作:SqlCommand sqlcom=new SqlCommand("insert into info(id,name,sex)values("+i+",'"+s 1+"','"+s2+"')",objSqlConnection);
sqlcom.ExecuteNonQuery();
填充:
DataTable dt1=new DataTable();
SqlDataAdapter da1=new SqlDataAdapter();
string query="SELECT*from info where id="+i;
DataSet objDataSet=new DataSet();
SqlDataAdapter obj=new SqlDataAdapter();
obj.SelectCommand=new SqlCommand(query,objSqlConnection);
obj.Fill(objDataSet,"info");
SqlCommand objSqlCommand=new SqlCommand(query,objSqlConnection);SqlDataRe ader objSqlReader=objSqlCommand.ExecuteReader();
数据库连接示例:
static public SqlConnection GetConn()
{
string connString = null;
connString =System.Configuration.ConfigurationManager.AppSettings["ConnString"]; SqlConnection conn = new SqlConnection(connString);
return conn;
}// 执行select语句,返回DataTable对象
static public DataTable QueryBySql(string sqlStr)
{
DataTable dt = null;
SqlConnection conn = null;
SqlDataAdapter da = null;
try
{
dt = new DataTable();
conn = GetConn();
da = new SqlDataAdapter(sqlStr, conn);
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dt.Dispose();
da.Dispose();
conn.close();
conn.Dispose();
}
return dt;
}
// 执行insert into、update、delete
static public int SqlCmdOperation(string sqlText)
{
SqlConnection conn = null;
SqlCommand cmd = null;
int count = 0;
try