- 爱易网页
-
C#教程
- 求C#的WINFORM MSSQL数据库操作实例
日期:2014-05-18 浏览次数:20996 次
求C#的WINFORM MSSQL数据库操作实例,在线等
为本人刚学数C#,现在求一个数据库C#的WINFORM数据库操作类,并含一个使用例子,谢谢.最好能简单讲解一下.
------解决方案--------------------
20分???
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication5
{
public class DBHelper
{
//string strAppConfigFile = ConfigurationManager.AppSettings["DataBaseType"].ToString();
//Helper _helper = new Helper();
//public Helper GetHelper()
//{
// switch (strAppConfigFile)
// {
// case "System.Data.OracleClient":
// _helper.DatabaseType = Helper.DatabaseTypes.Oracle;
// break;
// case "MySql.Data.MySqlClient":
// _helper.DatabaseType = Helper.DatabaseTypes.MySql;
// break;
// case "System.Data.OleDb":
// _helper.DatabaseType = Helper.DatabaseTypes.OleDb;
// break;
// case "System.Data.SqlClient":
// default:
// _helper.DatabaseType = Helper.DatabaseTypes.Sql;
// break;
// }
// return _helper;
//}
private static SqlConnection connection;
public static SqlConnection Connection
{
get
{
string connectionString = "server=MMIT017\\SQL2008;database=TestDB;uid=sa;pwd=123456";
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;
}
}
public static int ExecuteCommand(string safeSql)
{
SqlCommand cmd = new SqlCommand(safeSql, Connection);
int result = cmd.ExecuteNonQuery();
return result;
}
public static int ExecuteCommand(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
return cmd.ExecuteNonQuery();
}
public static int ExecuteCommand2(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
return cmd.ExecuteNonQuery();
}
public static string GetScalar(string safeSql)
{
SqlCommand cmd = new SqlCommand(safeSql, Connection);
string result = cmd.ExecuteScalar().ToString();
return result;
}
public string GetScalar(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
string result = cmd.ExecuteScalar().ToString();
return result;
}