使用using{},去掉数据库连接的.Close()方法,using自动会调用Dispose()来关闭数据库连接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.OleDb; namespace DormMIS { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Login : System.Windows.Forms.Form { private System.Windows.Forms.Button btClose;//取消按钮 private System.Windows.Forms.Button btAdd; private System.Windows.Forms.TextBox password; private System.Windows.Forms.TextBox name; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; private OleDbConnection oleConnection1 = null; public Login() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); this.oleConnection1=new OleDbConnection(DormMIS.database.dbConnection.connection); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login)); this.btClose = new System.Windows.Forms.Button(); this.btAdd = new System.Windows.Forms.Button(); this.password = new System.Windows.Forms.TextBox(); this.name = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // btClose // this.btClose.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btClose.ForeColor = System.Drawing.Color.Black; this.btClose.Location = new System.Drawing.Point(168, 156); this.btClose.Name = "btClose"; this.btClose.Size = new System.Drawing.Size(75, 23); this.btClose.TabIndex = 20; this.btClose.Text = "取消"; this.btClose.Click += new System.EventHandler(this.btClose_Click); // // btAdd // this.btAdd.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btAdd.ForeColor = System.Drawing.Color.Black; this.btAdd.Location = new System.Drawing.Point(48, 156); this.btAdd.Name = "btAdd"; this.btAdd.Size = new System.Drawing.Size(75, 23); this.btAdd.TabIndex = 19; this.btAdd.Text = "确定"; this.btAdd.Click += new System.EventHandler(this.btAdd_Click); // // password // this.password.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.password.Location = new System.Drawing.Point(128, 116); this.password.Name = "password"; this.password.PasswordChar = '*'; this.password.Size = new System.Drawing.Size(100, 21); this.password.TabIndex = 18; this.password.Text = "admin"; // // name // this.name.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.name.Location = new System.Drawing.Point(128, 76); this.name.Name = "name"; this.name.Size = new System.Drawing.Size(100, 21); this.name.TabIndex = 17; this.name.Text = "admin"; this.name.TextChanged += new System.EventHandler(this.name_TextChanged); // // label3 // this.label3.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label3.ForeColor = System.Drawing.Color.Black; this.label3.Location = new System.Drawing.Point(64, 116); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 23); this.label3.TabIndex = 16; this.label3.Text = "密 码"; // // label2 // this.label2.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label2.ForeColor = System.Drawing.Color.Black; this.label2.Location = new System.Drawing.Point(64, 76); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 23); this.label2.TabIndex = 15; this.label2.Text = "用户名"; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.ForeColor = System.Drawing.Color.Black; this.label1.Location = new System.Drawing.Point(40, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(228, 28); this.label1.TabIndex = 14; this.label1.Text = "宿舍管理信息系统"; // // Login // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.BackColor = System.Drawing.Color.Ivory; this.ClientSize = new System.Drawing.Size(304, 210); this.Controls.Add(this.btClose); this.Controls.Add(this.btAdd); this.Controls.Add(this.password); this.Controls.Add(this.name); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Login"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "登录"; this.Load += new System.EventHandler(this.Login_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Login()); } private void btAdd_Click(object sender, System.EventArgs e) { if(name.Text.Trim()==""||password.Text.Trim()=="") MessageBox.Show("请输入用户名和密码","提示"); else { oleConnection1.Open(); OleDbCommand cmd=new OleDbCommand("",oleConnection1); string sql="select * from userinfo where UName='"+name.Text.Trim()+"' and PWD='"+password.Text.Trim()+"'"; cmd.CommandText=sql; if (null!=cmd.ExecuteScalar()) { //隐藏登录窗口 this.Visible=false; //创建并打开主界面 Main main=new Main(); main.Tag=this.FindForm(); OleDbDataReader dr; cmd.CommandText=sql; dr=cmd.ExecuteReader(); dr.Read(); main.statusBarPanel2.Text=name.Text.Trim(); main.ShowDialog(); } else MessageBox.Show("用户名或密码错误","警告"); } oleConnection1.Close(); } private void btClose_Click(object sender, System.EventArgs e) { this.Close(); } private void name_TextChanged(object sender, EventArgs e) { } } }
一款特别好用的.net数据库链接通用类。 using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Data.Common; using System.Collections.Generic; namespace CMS.DBUtility { /// <summary> /// 数据访问抽象基础类 /// Copyright (C) 2004-2008 By LiTianPing /// </summary> public abstract class DbHelperSQL { //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. public static string connectionString = PubConstant.ConnectionString; public DbHelperSQL() { } #region 公用方法 /// <summary> /// 判断是否存在某表的某个字段 /// </summary> /// <param name="tableName">表名称</param> /// <param name="columnName">列名称</param> /// <returns>是否存在</returns> public static bool ColumnExists(string tableName, string columnName) { string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; object res = GetSingle(sql); if (res == null) { return false; } return Convert.ToInt32(res) > 0; } public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } /// <summary> /// 表是否存在 /// </summary> /// <param name="TableName"></param> /// <returns></returns> public static bool TabExists(string TableName) { string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1"; //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')"; object obj = GetSingle(strsql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params SqlParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } public static int ExecuteSqlByTime(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行Sql和Oracle滴混合事务 /// </summary> /// <param name="list">SQL命令行列表</param> /// <param name="oracleCmdSqlList">Oracle命令行列表</param> /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns> public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { foreach (CommandInfo myDE in list) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, tx, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.SolicitationEvent) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (isHave) { //引发事件 myDE.OnSolicitationEvent(); } } if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0"); //return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0"); //return 0; } continue; } int val = cmd.ExecuteNonQuery(); if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行"); //return 0; } cmd.Parameters.Clear(); } string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC"); bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList); if (!res) { tx.Rollback(); throw new Exception("Oracle执行失败"); // return -1; } tx.Commit(); return 1; } catch (System.Data.SqlClient.SqlException e) { tx.Rollback(); throw e; } catch (Exception e) { tx.Rollback(); throw e; } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static int ExecuteSqlTran(List<String> SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static object ExecuteSqlGet(string SQLString, string content) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } public static object GetSingle(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string strSQL) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int count = 0; //循环 foreach (CommandInfo myDE in cmdList) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { trans.Rollback(); return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { trans.Rollback(); return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { trans.Rollback(); return 0; } continue; } int val = cmd.ExecuteNonQuery(); count += val; if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { trans.Rollback(); return 0; } cmd.Parameters.Clear(); } trans.Commit(); return count; } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; //循环 foreach (CommandInfo myDE in SQLStringList) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } // finally // { // cmd.Dispose(); // connection.Close(); // } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; 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); } } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程,返回SqlDataReader ( 注意:调用方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlDataReader</returns> public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); SqlDataReader returnReader; connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="tableName">DataSet结果中的表名</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } /// <summary> /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand</returns> private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { 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); } } return command; } /// <summary> /// 执行存储过程,返回影响的行数 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="rowsAffected">影响的行数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { int result; connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; //Connection.Close(); return result; } } /// <summary> /// 创建 SqlCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand 对象实例</returns> private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } #endregion } }
/* API精灵 FOR C# 开始设计日期 2004.03.06 设计目的:简单快速对C#中使用的API函数进行查询,并给出调用代码 设计进度: 2004.03.09 完成对的查询功能,包括 代码调用,中文注释,所需的DLL库,与C#中函数对应关系 2004.03.10 0:48:52 完成了用StringBuilder数组对原ComboBox的替换,可以使程序不用从新读取数据库就可以刷新修改后的信息! 2004.03.10 18:00:00 完成了用ArrayList对StringBuilder数组的替换节省2M内存 2004.03.11 21:10:15 完成滚动字幕的设置,启用了一个TIMER控件,然后设置时间,删除字符串的第一个字母已达到滚动效果! 2004.03.11 22:02:00 改正更新时出现空值出错问题,新填函数isnull 2004.03.12 13:22:08 完成关键字高亮显示 高亮显示函数 mykeywords 2004.03.12 22:08:20 加强了高亮显示函数 mykeywords的功能,使其能识别不同的关键字并显示不同的颜色 2004.03.14 01:40:00 完成对CONST的查询,并且增加了 mykeywords1函数,使其关键字显示性能提高 2004.03.14 13:12:00 添加了提示信息,提示信息设置在函数 mytips() 中 2004.03.15 21:51:20 更改数据库和WINAPI.TXT路径为程序运行路径 2004.03.15 22:31:50 添加了鼠标右键信息 2004.03.15 23.23:30 添加了数据库密码 2004.03.16 23:24:30 添加了版权信息以及相应提示 */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.OleDb; using System.Runtime.InteropServices; using System.IO; namespace API精灵 { /// /// Form1 的摘要说明。 /// 这个版本没有使用oleDbDataAdapter+DataSet对数据进行存取,而是使用的OleDbCommand +OleDbDataReader 的形式。 /// 主要是想试验一下不用oleDbDataAdapter+DataSet的数据存取速度。 /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Button button4; private System.Windows.Forms.TextBox mysearch; private System.Windows.Forms.ListBox tiplist; private System.Windows.Forms.ComboBox select_type; private System.Windows.Forms.TextBox dlltext; /// /// 必需的设计器变量。 /// //自定义变量 private ArrayList fundll = new ArrayList();//保存读取出来的DLL内容 private ArrayList funtips = new ArrayList();//保存读取出来的中文提示信息 private ArrayList funcode = new ArrayList();//保存读取出来的C#调用代码 private ArrayList funmat = new ArrayList();//保存读取出来的C#对应函数 private ArrayList funwin9x = new ArrayList();//保存读取出来的WIN9X private ArrayList funwin2k = new ArrayList();//保存读取出来的WIN2K private int nowselect = 0; private string oldscoll_text; private int nowtypeselect = 0; private string nowpath = @System.Environment.CurrentDirectory+@"\"; private string dbpassword = "ling_feng_work"; public string myConnstr; public OleDbConnection myconn ;//创建一个新连接 private string mysql ;//查询语句 private string sql_update; private System.Windows.Forms.RichTextBox tipsmemo; private System.Windows.Forms.TextBox mat_text; private OleDbCommand mycommand = new OleDbCommand(); private System.Windows.Forms.RichTextBox codememo; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.CheckBox win9x; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.CheckBox win2k; private System.Windows.Forms.CheckBox e_add; private System.Windows.Forms.CheckBox e_modify; private System.Windows.Forms.Button b_modify; private System.Windows.Forms.Button b_add; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.ContextMenu mypop; private System.Windows.Forms.MenuItem menuItem1; private System.ComponentModel.IContainer components; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.button1 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tiplist = new System.Windows.Forms.ListBox(); this.select_type = new System.Windows.Forms.ComboBox(); this.mat_text = new System.Windows.Forms.TextBox(); this.mysearch = new System.Windows.Forms.TextBox(); this.dlltext = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.tipsmemo = new System.Windows.Forms.RichTextBox(); this.mypop = new System.Windows.Forms.ContextMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.codememo = new System.Windows.Forms.RichTextBox(); this.b_modify = new System.Windows.Forms.Button(); this.b_add = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.win2k = new System.Windows.Forms.CheckBox(); this.win9x = new System.Windows.Forms.CheckBox(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.e_add = new System.Windows.Forms.CheckBox(); this.e_modify = new System.Windows.Forms.CheckBox(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.groupBox5.SuspendLayout(); this.SuspendLayout(); // // button1 // this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.Location = new System.Drawing.Point(224, 395); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 24); this.button1.TabIndex = 10; this.button1.Text = "关 于"; this.button1.Click += new System.EventHandler(this.button1_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.tiplist); this.groupBox1.Controls.Add(this.select_type); this.groupBox1.Controls.Add(this.mat_text); this.groupBox1.Controls.Add(this.mysearch); this.groupBox1.Controls.Add(this.dlltext); this.groupBox1.Location = new System.Drawing.Point(8, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(200, 168); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "API查询"; // // tiplist // this.tiplist.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tiplist.ItemHeight = 12; this.tiplist.Location = new System.Drawing.Point(8, 43); this.tiplist.Name = "tiplist"; this.tiplist.Size = new System.Drawing.Size(184, 110); this.tiplist.TabIndex = 1; this.tiplist.Visible = false; this.tiplist.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tiplist_KeyDown); this.tiplist.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tiplist_KeyPress); this.tiplist.DoubleClick += new System.EventHandler(this.tiplist_DoubleClick); this.tiplist.MouseUp += new System.Windows.Forms.MouseEventHandler(this.tiplist_MouseUp); this.tiplist.MouseLeave += new System.EventHandler(this.tiplist_MouseLeave); this.tiplist.SelectedIndexChanged += new System.EventHandler(this.tiplist_SelectedIndexChanged); // // select_type // this.select_type.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.select_type.Items.AddRange(new object[] { "API函数查询", "常量定义查询"}); this.select_type.Location = new System.Drawing.Point(8, 61); this.select_type.Name = "select_type"; this.select_type.Size = new System.Drawing.Size(184, 20); this.select_type.TabIndex = 2; this.select_type.SelectedIndexChanged += new System.EventHandler(this.select_type_SelectedIndexChanged); // // mat_text // this.mat_text.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.mat_text.Location = new System.Drawing.Point(8, 134); this.mat_text.Name = "mat_text"; this.mat_text.Size = new System.Drawing.Size(184, 21); this.mat_text.TabIndex = 4; this.mat_text.Text = "C#对应函数:"; this.mat_text.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mat_text_MouseDown); // // mysearch // this.mysearch.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.mysearch.Location = new System.Drawing.Point(8, 24); this.mysearch.Name = "mysearch"; this.mysearch.Size = new System.Drawing.Size(184, 21); this.mysearch.TabIndex = 0; this.mysearch.Text = ""; this.mysearch.KeyDown += new System.Windows.Forms.KeyEventHandler(this.mysearch_KeyDown); this.mysearch.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mysearch_MouseDown); this.mysearch.TextChanged += new System.EventHandler(this.mysearch_TextChanged); // // dlltext // this.dlltext.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.dlltext.Location = new System.Drawing.Point(8, 97); this.dlltext.Name = "dlltext"; this.dlltext.Size = new System.Drawing.Size(184, 21); this.dlltext.TabIndex = 3; this.dlltext.Text = ""; this.dlltext.TextChanged += new System.EventHandler(this.dlltext_TextChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.tipsmemo); this.groupBox2.Location = new System.Drawing.Point(216, 8); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(200, 168); this.groupBox2.TabIndex = 2; this.groupBox2.TabStop = false; this.groupBox2.Text = "函数注释"; // // tipsmemo // this.tipsmemo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tipsmemo.ContextMenu = this.mypop; this.tipsmemo.Location = new System.Drawing.Point(8, 16); this.tipsmemo.Name = "tipsmemo"; this.tipsmemo.Size = new System.Drawing.Size(184, 144); this.tipsmemo.TabIndex = 0; this.tipsmemo.Text = ""; this.tipsmemo.MouseEnter += new System.EventHandler(this.richTextBox1_MouseEnter); // // mypop // this.mypop.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.Text = "复制信息"; this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); // // groupBox3 // this.groupBox3.Controls.Add(this.codememo); this.groupBox3.Location = new System.Drawing.Point(8, 221); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(408, 168); this.groupBox3.TabIndex = 3; this.groupBox3.TabStop = false; this.groupBox3.Text = "代码调用"; // // codememo // this.codememo.ContextMenu = this.mypop; this.codememo.Location = new System.Drawing.Point(8, 16); this.codememo.Name = "codememo"; this.codememo.Size = new System.Drawing.Size(392, 144); this.codememo.TabIndex = 0; this.codememo.Text = ""; this.codememo.TextChanged += new System.EventHandler(this.codememo_TextChanged); // // b_modify // this.b_modify.Enabled = false; this.b_modify.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.b_modify.Location = new System.Drawing.Point(120, 395); this.b_modify.Name = "b_modify"; this.b_modify.Size = new System.Drawing.Size(75, 24); this.b_modify.TabIndex = 4; this.b_modify.Text = "修改信息"; this.b_modify.Click += new System.EventHandler(this.button2_Click); // // b_add // this.b_add.Enabled = false; this.b_add.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.b_add.Location = new System.Drawing.Point(16, 395); this.b_add.Name = "b_add"; this.b_add.Size = new System.Drawing.Size(75, 24); this.b_add.TabIndex = 5; this.b_add.Text = "添加新项"; // // button4 // this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button4.Location = new System.Drawing.Point(328, 395); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 24); this.button4.TabIndex = 6; this.button4.Text = "退 出"; this.button4.Click += new System.EventHandler(this.button4_Click); // // groupBox4 // this.groupBox4.Controls.Add(this.win2k); this.groupBox4.Controls.Add(this.win9x); this.groupBox4.Location = new System.Drawing.Point(8, 176); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(200, 40); this.groupBox4.TabIndex = 11; this.groupBox4.TabStop = false; // // win2k // this.win2k.Location = new System.Drawing.Point(104, 11); this.win2k.Name = "win2k"; this.win2k.Size = new System.Drawing.Size(80, 24); this.win2k.TabIndex = 1; this.win2k.Text = "支持win2k"; // // win9x // this.win9x.Location = new System.Drawing.Point(16, 11); this.win9x.Name = "win9x"; this.win9x.TabIndex = 0; this.win9x.Text = "支持win9x"; // // groupBox5 // this.groupBox5.Controls.Add(this.e_add); this.groupBox5.Controls.Add(this.e_modify); this.groupBox5.Location = new System.Drawing.Point(216, 176); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(200, 40); this.groupBox5.TabIndex = 12; this.groupBox5.TabStop = false; // // e_add // this.e_add.Location = new System.Drawing.Point(112, 10); this.e_add.Name = "e_add"; this.e_add.Size = new System.Drawing.Size(80, 24); this.e_add.TabIndex = 5; this.e_add.Text = "允许添加"; this.e_add.CheckedChanged += new System.EventHandler(this.e_add_CheckedChanged); // // e_modify // this.e_modify.Location = new System.Drawing.Point(16, 10); this.e_modify.Name = "e_modify"; this.e_modify.Size = new System.Drawing.Size(76, 24); this.e_modify.TabIndex = 4; this.e_modify.Text = "允许修改"; this.e_modify.CheckedChanged += new System.EventHandler(this.e_modify_CheckedChanged); // // timer1 // this.timer1.Interval = 500; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(424, 429); this.Controls.Add(this.groupBox5); this.Controls.Add(this.groupBox4); this.Controls.Add(this.button4); this.Controls.Add(this.b_add); this.Controls.Add(this.b_modify); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox1); this.Controls.Add(this.button1); this.Controls.Add(this.groupBox2); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "API精灵FOR C#"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox4.ResumeLayout(false); this.groupBox5.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.Run(new Form1()); } [DllImport("user32.dll", EntryPoint="ShowWindow")] public static extern int ShowWindow ( int hwnd, int nCmdShow ); private void button1_Click(object sender, System.EventArgs e) { AboutForm myabout = new AboutForm(); myabout.ShowDialog(); } /// /// 填写mysearch中的内容。 /// private void search_comp() { if (tiplist.SelectedIndex>-1) mysearch.Text = tiplist.SelectedItem.ToString(); tiplist.Visible = false ; mysearch.Select(); } /// /// 自动填写提示内容。 /// private void autocomp() { if (tiplist.SelectedIndex>-1) try { if (this.nowtypeselect==0) //================查询函数 { this.nowselect = tiplist.SelectedIndex; dlltext.Text = fundll[tiplist.SelectedIndex].ToString();//else tipsmemo.Text = funtips[tiplist.SelectedIndex].ToString(); codememo.Text = funcode[tiplist.SelectedIndex].ToString(); mat_text.Text = funmat[tiplist.SelectedIndex].ToString(); this.oldscoll_text = mat_text.Text; if (funwin9x[tiplist.SelectedIndex].ToString()==("Yes")) win9x.Checked=true; else win9x.Checked=false; if (funwin2k[tiplist.SelectedIndex].ToString()==("Yes")) win2k.Checked=true; else win2k.Checked=false; //滚动文字 if (mat_text.TextLength>30) timer1.Enabled = true; else timer1.Enabled = false; } else { dlltext.Text = ""; tipsmemo.Text = ""; codememo.Text = ""; win9x.Checked = false; win2k.Checked = false; } //******************** if (this.nowtypeselect==1) { this.nowselect = tiplist.SelectedIndex; codememo.Text = funcode[tiplist.SelectedIndex].ToString(); } //******************** //================= } catch { dlltext.Text = "没有找到相应连接库"; tipsmemo.Text = "没有找到相应提示"; codememo.Text = "没有找到相应调用代码"; mat_text.Text = "没有找到相应C#函数"; } } // /// /// 手动释放一些内存。 /// private void mydisp() { tipsmemo.Clear(); codememo.Clear(); tiplist.Items.Clear(); // ===== fundll.Clear();//保存读取出来的DLL内容 funtips.Clear();//保存读取出来的中文提示信息 funcode.Clear();//保存读取出来的C#调用代码 funmat.Clear();//保存读取出来的C#对应函数 funwin9x.Clear();//保存读取出来的WIN9X funwin2k.Clear();//保存读取出来的WIN2K } private void mysearch_TextChanged(object sender, System.EventArgs e) { tiplist.Visible = true ; //自动完成功能。 tiplist.SelectedIndex = (tiplist.FindString(mysearch.Text,-1)) ;//加上这句,保证TIPLIST跟着自动变化 nowselect = tiplist.SelectedIndex; autocomp(); //设置提示信息 mytips(); } private void mysearch_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if ((e.KeyCode == Keys.Down) || (e.KeyCode == Keys.Up)) tiplist.Focus(); if (e.KeyCode == Keys.Enter) { search_comp(); if (this.nowtypeselect==0) mykeyword(); if (this.nowtypeselect==1) mykeyword1(); } if (e.KeyCode == Keys.Escape) { tiplist.Visible = false ; } } private void tiplist_MouseLeave(object sender, System.EventArgs e) { } private void tiplist_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { } private void tiplist_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.search_comp(); if (this.nowtypeselect==0) mykeyword(); else mykeyword1(); } if (e.KeyCode == Keys.Escape) { tiplist.Visible = false ; } } private void tiplist_DoubleClick(object sender, System.EventArgs e) { this.search_comp(); if (this.nowtypeselect==0) mykeyword(); else mykeyword1(); } private void Form1_Load(object sender, System.EventArgs e) { //初始化数据库 initdatabase(); //MessageBox.Show(this,"欢迎使用 共享版\n 本版对使用功能上略有限制\n 且不提供数据库更新!\n 如想获得更多信息请与我联系。\n dong_teng@tom.com","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); select_type.SelectedIndex = 0; AboutForm myabout = new AboutForm(); myabout.ShowDialog(); } // private void mytips() { //设置提示信息 if ((this.nowselect>-1)&(this.nowtypeselect==0)) { toolTip1.SetToolTip(this.dlltext,"所在动态连接库: "+this.fundll[this.nowselect].ToString()); toolTip1.SetToolTip(this.mat_text,"在C#中对应的函数: "+this.funmat[this.nowselect].ToString()); toolTip1.SetToolTip(this.codememo,"函数 "+this.tiplist.SelectedItem.ToString()+" 在C#中的调用代码,可以手动修改"); toolTip1.SetToolTip(this.tipsmemo,"函数 "+this.tiplist.SelectedItem.ToString()+" 的注释信息,可以手动修改"); } else if ((this.nowselect>-1)&(this.nowtypeselect==1)) { toolTip1.SetToolTip(this.codememo,"常量 "+this.tiplist.SelectedItem.ToString()+" 在C#中的调用代码"); toolTip1.SetToolTip(this.dlltext,"没有相关信息"); toolTip1.SetToolTip(this.mat_text,"没有相关信息"); toolTip1.SetToolTip(this.tipsmemo,"没有相关信息"); } } // private void initdatabase() { string dbpath = @nowpath+"winapi.mdb"; tiplist.Items.Clear(); //@"Provider=Microsoft.Jet.OleDB.4.0;Data Source="+dbpath+";User Id=admin;Password="+this.dbpassword ; //"Provider=Microsoft.Jet.OleDB.4.0;Data Source=your mdb filename;Jet OLEDB:Database Password='pass'" ; this.myConnstr = @"Provider=Microsoft.Jet.OleDB.4.0;Data Source="+dbpath+";User Id=admin;Jet OLEDB:Database Password="+this.dbpassword ; this.myconn= new OleDbConnection(myConnstr); mysql= @"select Fun_name,Fun_dll,Fun_tips,Fun_code,Fun_com,win9x,win2k from winapi"; using(myconn) { myconn.Open(); // if (myconn.State.ToString() == "Open") MessageBox.Show("打开成功!"); //数据处理 // OleDbCommand mycommand = new OleDbCommand(mysql,myconn); mycommand.CommandText = mysql; mycommand.Connection = myconn; OleDbDataReader myreader = mycommand.ExecuteReader(); int i=0; while (myreader.Read()) { tiplist.Items.Add(myreader["Fun_name"]); fundll.Add(myreader["fun_dll"].ToString()); funtips.Add(myreader["fun_tips"].ToString()); funcode.Add(myreader["fun_code"].ToString()); funmat.Add(myreader["fun_com"].ToString()); funwin9x.Add(myreader["win9x"].ToString()); funwin2k.Add(myreader["win2k"].ToString()); i++; } myconn.Close(); myreader.Close(); } } //更新缓存 private void memo_update() { fundll[nowselect] = dlltext.Text; funtips[nowselect] = this.tipsmemo.Text; funcode[nowselect] = this.codememo.Text; funmat[nowselect] = this.mat_text.Text; if (win9x.Checked) funwin9x[nowselect]="Yes" ;else funwin9x[nowselect]="No"; if (win2k.Checked) funwin2k[nowselect]="Yes" ;else funwin2k[nowselect]="No"; } // private void oleDbConnection1_InfoMessage(object sender, System.Data.OleDb.OleDbInfoMessageEventArgs e) { } //==============从WINAPI.TXT读取CONST并拆分 private void mysplip() { //string dbpath = @System.Environment.CurrentDirectory+@"\winapi.mdb"; string filename =@nowpath +"winapi.txt"; string nextline; tiplist.Items.Clear(); StreamReader sr = new StreamReader(filename); while ((nextline = sr.ReadLine())!=null) { if (nextline.StartsWith("public const")) { string[] ss = nextline.Split('='); tiplist.Items.Add(ss[0].Substring(16).Trim()); funcode.Add(nextline); } } sr.Close(); } //============================== private void select_type_SelectedIndexChanged(object sender, System.EventArgs e) { if (select_type.SelectedIndex != this.nowtypeselect) { this.mydisp(); switch (select_type.SelectedIndex) { case 0:initdatabase();this.nowtypeselect=select_type.SelectedIndex;break; case 1:mysplip();this.nowtypeselect=select_type.SelectedIndex;this.dlltext.Clear();this.mat_text.Clear();break; } isenable(this.nowtypeselect); } } private void dlltext_TextChanged(object sender, System.EventArgs e) { } private void richTextBox1_MouseEnter(object sender, System.EventArgs e) { tiplist.Visible = false ; } private void mysearch_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { tiplist.Visible = false ; mysearch.Focus(); } private void tiplist_SelectedIndexChanged(object sender, System.EventArgs e) { autocomp(); } /// /// 修改内容。 /// private void fun_update() { using(myconn) { myconn.ConnectionString = myConnstr; myconn.Open(); try { //if (myconn.State.ToString() == "Open") MessageBox.Show("打开成功!"); isnull();//判断是否有无效值 string str_win9x,str_win2k; if (win9x.Checked) str_win9x = "Yes" ; else str_win9x = "No"; if (win2k.Checked) str_win2k = "Yes" ; else str_win2k = "No"; sql_update = "update winapi set Fun_dll = '"+dlltext.Text+"'"+" , Fun_tips = '"+tipsmemo.Text+"'"+" , Fun_code = '"+codememo.Text+"'"+" , Fun_com ='"+mat_text.Text+"' "; sql_update +=" , win9x = '" + str_win9x +"' " + ", win2k = '" + str_win2k+"' "; sql_update +=" where Fun_name ='"+ mysearch.Text+"'"; mycommand.Connection = myconn; mycommand.CommandText = sql_update; mycommand.ExecuteNonQuery(); myconn.Close(); memo_update(); MessageBox.Show(this,"恭喜!更新成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } catch { // tipsmemo.Text = sql_update; MessageBox.Show("没有找到相应记录,更新失败!"); } } } //判断是更新的部分是否有效(不能为空) private void isnull() { if (this.mat_text.Text=="") this.mat_text.Text="没有相关信息"; if (this.codememo.Text=="") this.codememo.Text="没有相关信息"; if (this.tipsmemo.Text=="") this.tipsmemo.Text="没有相关信息"; if (this.dlltext.Text=="") this.dlltext.Text="没有相关信息"; } //关键字高亮显示 private void mykeyword() { string[] keywords = new string[5]; keywords[0]=mysearch.Text; keywords[1]="string"; keywords[2]="ref"; keywords[3]="int"; keywords[4]="static extern"; for(int i=0;i0) { index++; switch(i) { case 0: codememo.SelectionColor = Color.Red;break; case 1: codememo.SelectionColor = Color.Green;break; case 2: codememo.SelectionColor = Color.Brown;break; case 3: codememo.SelectionColor = Color.Blue;break; case 4: codememo.SelectionColor = Color.Green;break; //default:codememo.SelectionColor = Color.Blue;break; } } } } // //CONST中关键字高亮显示 private void mykeyword1() { string[] keywords = new string[5]; keywords[0]=mysearch.Text; keywords[1]="="; keywords[2]="0"; keywords[3]="int"; keywords[4]="const"; for(int i=0;i0) { index++; switch(i) { case 0: codememo.SelectionColor = Color.Red;break; case 1: codememo.SelectionColor = Color.Blue;break; case 2: codememo.SelectionColor = Color.Green;break; case 3: codememo.SelectionColor = Color.Blue;break; case 4: codememo.SelectionColor = Color.Green;break; //default:codememo.SelectionColor = Color.Blue;break; } if (index>codememo.TextLength) break; } } } // private void button2_Click(object sender, System.EventArgs e) { this.fun_update(); } private void isenable(int i_temp) { if (i_temp==0) { win9x.Enabled=true; win2k.Enabled=true; e_modify.Enabled=true; e_add.Enabled=true; b_modify.Enabled=true; b_add.Enabled=true; } else { win9x.Enabled=false; win2k.Enabled=false; e_modify.Enabled=false; e_add.Enabled=false; b_modify.Enabled=false; b_add.Enabled=false; } } private void button4_Click(object sender, System.EventArgs e) { Application.Exit(); } private void e_modify_CheckedChanged(object sender, System.EventArgs e) { if (e_modify.Checked) b_modify.Enabled = true; else b_modify.Enabled = false; } private void e_add_CheckedChanged(object sender, System.EventArgs e) { if (e_add.Checked) b_add.Enabled = true; else b_add.Enabled = false; } private void timer1_Tick(object sender, System.EventArgs e) { if (this.mat_text.TextLength>0) mat_text.Text = mat_text.Text.Remove(0,1); else mat_text.Text = oldscoll_text; } private void mat_text_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { timer1.Enabled = false ; mat_text.Text = oldscoll_text; } private void codememo_TextChanged(object sender, System.EventArgs e) { } private void tiplist_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { } private void menuItem1_Click(object sender, System.EventArgs e) { Control ct = this.ActiveControl; string temp = ct.Text; Clipboard.SetDataObject(temp); } private void menuItem2_Click(object sender, System.EventArgs e) { } } }
4 浏览器网络编程(共两周) 4.1 浏览器工作原理(老师讲解1学时,学生理解1学时) 浏览器工作原理如图4-1所示。 图4-1 浏览器工作原理 (1) 浏览器分析超链指向页面的 URL。 (2) 浏览器向 DNS 请求解析 www.tsinghua.edu.cn 的 IP 地址。 (3) 域名系统 DNS 解析出清华大学服务器的 IP 地址。 (4) 浏览器与服务器建立 TCP 连接 (5) 浏览器发出取文件命令: GET /chn/yxsz/index.htm。 (6) 服务器 给出响应,把文件 index.htm 发给浏览器。 (7) TCP 连接释放。 (8) 浏览器显示“清华大学院系设置”文件 index.htm 中的所有文本 4.2 浏览器功能结构(老师讲解1学时,学生理解1学时) 浏览器程序功能结构如图4-2所示。 图4-2 浏览器功能结构 1) 浏览器有一组客户、一组解释程序,以及管理这些客户和解释程序的控制程序。 2) 控制程序是其中的核心部件,它解释鼠标的点击和键盘的输入,并调用有关的组件来执行用户指定的操作。 3) 例如,当用户用鼠标点击一个超链的起点时,控制程序就调用一个客户从所需文档所在的远地服务器上取回该文档,并调用解释程序向用户显示该文档 4) HTML 解释程序是必不可少的,而其他的解释程序则是可选的。 5) 解释程序把 HTML 规格转换为适合用户显示硬件的命令来处理版面的细节。 6) 许多浏览器还包含 FTP 客户,用来获取文件传送服务。 7) 一些浏览器也包含电子邮件客户,使浏览器能够发送和接收电子邮件 8) 浏览器将它取回的每一个页面副本都放入本地磁盘的缓存中。 9) 当用户用鼠标点击某个选项时,浏览器首先检查磁盘的缓存。若缓存中保存了该项,浏览器就直接从缓存中得到该项副本而不必从网络获取,这样就明显地改善浏览器的运行特性。 10) 但缓存要占用磁盘大量的空间,而浏览器性能的改善只有在用户再次查看缓存中的页面时才有帮助。 11) 许多浏览器允许用户调整缓存策略。 4.3 浏览器设计(老师讲解2学时,学生设计2学时) (1)浏览器功能设计 浏览器功能设计主要确定设计好的浏览器需要具备哪些功能,以及这些功能是以什么方式进行实现,这个步骤相当于软件设计中的“需求分析”,其中必须保证基本功能的具备,即浏览器必须能够浏览Web页面。 (2)浏览器界面设计 浏览器界面设计主要确定浏览器的页面布局,设定浏览器窗口上设置哪些功能菜单项、设置哪些功能按钮、设置哪些状态栏,它们各自的位置如何、属性如何、对应的变量如何等等。 (3)浏览器代码设计 浏览器代码设计主要是确定对上述的设计的功能在代码上怎样实现,包括选用的程序语言和编程平台选择、程序代码的编写、程序代码的调试、程序功能的测试等等。 4.4 浏览器编程设计平台(老师讲解2学时,学生理解4学时) (1)VS2005编程平台 (2)WebBrowser类及其使用 (3)一些浏览器程序的代码分析 4.5 浏览器开发步骤(8天) (1)熟悉VS2005平台,建立项目(半天) 打开VS2005选择“创建项目”,进入“新建项目”对话框,如图4-1所示。 图4-1 “新建项目”对话框 在“新建项目”对话框的项目类型窗口中选中“Visual C#”作为项目开发语言,在模板窗口中选中“Windows 应用程序”作为项目开发模板,在“名称”、“位置”编辑框中输入自己设定的项目名字和项目存储位置,本讲义使用“CSharp浏览器”作为项目名称,如图4-2所示。 图4-2 输入新建项目的属性 完成输入内容后,单击“确定”按钮,进入项目VC#开发窗口“Form.cs[设计]”,如图4-3所示。 图4-3 VC#开发窗口“Form.cs[设计]” (2)界面设计(1天) ○1设计菜单栏如图4-4所示。(半天) 图4-4 设计菜单栏 设计“文件”菜单如4-5所示。 图4-5 设计“文件”菜单 设计“编辑”菜单如图4-6所示。 图4-6 设计“编辑”菜单 设计“查看”菜单如图4-7所示。 图4-7 设计“查看”菜单 设计“收藏”菜单如图4-8所示。 图4-8 设计“收藏”菜单 设计“工具”菜单如图4-9所示。 图4-9 设计“工具”菜单 ○2设计工具栏、用户区和状态栏如图4-10所示(半天) 图4-10 工具栏和状态栏 (3)功能代码编辑 ○1初始化代码(半天) 双击“Form”设计页面进入代码编写页面,如图4-11所示。 图4-11 代码编写页面 初始化页面代码如下: ////////////////////////////////////////////////////////
### 回答1: 下面是一个基本的使用SqlConnection连接数据库的代码示例: ```csharp using System.Data.SqlClient; // 连接字符串 string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"; // 创建SqlConnection对象 SqlConnection conn = new SqlConnection(connectionString); // 打开连接 conn.Open(); // 执行查询等操作 // ... // 关闭连接 conn.Close(); ``` 在上面的代码示例中,我们首先指定了一个连接字符串,然后使用该连接字符串创建了一个SqlConnection对象。接着,我们调用`Open()`方法打开连接,执行需要的查询、添加、修改或删除等操作。最后,我们调用`Close()`方法关闭连接。需要注意的是,SqlConnection对象是实现了IDisposable接口的,因此在使用完成后可以通过调用Dispose()方法来释放资源。 ### 回答2: 在Visual Studio中使用C#编写数据库连接代码可以通过ADO.NET提供的SqlConnection类来实现。 首先,需要在项目中添加对System.Data.SqlClient命名空间的引用。 然后,可以使用以下代码来建立与数据库的连接并执行一些操作: ```csharp using System.Data.SqlClient; class Program { static void Main(string[] args) { // 建立与数据库的连接 string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabaseName;Integrated Security=True"; using (SqlConnection conn = new SqlConnection(connectionString)) { try { // 打开连接 conn.Open(); // 执行一些数据库操作 // 例如执行一个查询 string query = "SELECT * FROM YourTableName"; using (SqlCommand command = new SqlCommand(query, conn)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // 处理查询结果 // 例如获取某列的值 string value = reader.GetString(0); Console.WriteLine(value); } } } } catch (SqlException ex) { // 处理连接或数据库操作可能出现的异常 Console.WriteLine("连接或操作数据库时出错:" + ex.Message); } } } } ``` 以上代码中,首先通过设置connectionString来指定数据库连接的相关信息,包括数据库服务器、数据库名称以及身份验证方式。 接着,使用using语句创建SqlConnection对象,并传入连接字符串。在using代码块中,打开连接,执行一些数据库操作,例如查询数据,并在之后的代码中处理查询结果。 最后,在catch代码块中处理可能出现的SqlException异常,例如连接或操作数据库时出现的错误信息。 需要注意的是,这只是一个简单的连接数据库的示例,实际使用时可能需要根据具体情况进行修改和扩展。 ### 回答3: 在Visual Studio中连接数据库需要使用ADO.NET来实现。以下是一个使用C#语言的示例代码: ``` using System; using System.Data.SqlClient; class Program { static void Main(string[] args) { // 数据库连接字符串 string connString = "Server=服务器地址;Database=数据库名称;User Id=用户名;Password=密码;"; try { // 创建连接对象 SqlConnection conn = new SqlConnection(connString); // 打开数据库连接 conn.Open(); // 连接成功后,可以执行数据库操作,比如执行SQL语句查询数据 // 关闭数据库连接 conn.Close(); } catch (SqlException ex) { // 处理数据库连接失败的异常 Console.WriteLine("数据库连接失败:" + ex.Message); } catch (Exception ex) { // 处理其他异常 Console.WriteLine("发生异常:" + ex.Message); } Console.ReadKey(); } } ``` 请注意替换代码中的服务器地址、数据库名称、用户名和密码为实际的数据库信息。以上代码实现了打开数据库连接、执行数据库操作以及关闭数据库连接的过程,并捕获了可能发生的异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值