2 z420038848 z420038848 于 2013.08.07 16:04 提问

C#链接数据库问题!!!!
c#

我是个刚学C#的初学者,我写了一个登录界面,现在不知道怎么链接数据库,也不知道用哪一种数据库,不知道是不是可以用Access,如果可以用请各位大神给个实例或教我一下好行。

2个回答

u012003714
u012003714   2013.09.18 11:28
已采纳

你可以封装一个SQLHELP的类 代码如下:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebApplication1
{
public class SQLHELP
{
static string config = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;//配置文件
public static int ExecuteNonQuery(string sql, params SqlParameter[] Parameter)//申明一个ExecuteNonQuery方法 params代表部分参数
{
using (SqlConnection conn = new SqlConnection(config))//数据库的连接
{
conn.Open();
using (SqlCommand comm = conn.CreateCommand())
{
comm.CommandText = sql;//sql语句
comm.Parameters.AddRange(Parameter);
return comm.ExecuteNonQuery();//返回申明的ExecuteNonQuery 是返回一条查询记录
}
}

    }

    public static string ExecuteScalar(string sql, params SqlParameter[] Parameter)//申明一个类型为object ExecuteScalar的方法名
    {
        using (SqlConnection conn = new SqlConnection(config))//数据库连接
        {
            conn.Open();
            using (SqlCommand comm = conn.CreateCommand())
            {
                comm.CommandText = sql;
                comm.Parameters.AddRange(Parameter);
                return comm.ExecuteScalar().ToString();//ExecuteScalar返回的是多条查询记录
            }
        }
    }

    public static DataTable ExecuteDataTable(string sql, params SqlParameter[] Parameter)//此方法返回DataSet对象,该对象包含由某一命令返回的结果集
    {
        using (SqlConnection conn = new SqlConnection(config))
        {
            conn.Open();
            using (SqlCommand comm = conn.CreateCommand())
            {
                comm.CommandText = sql;
                comm.Parameters.AddRange(Parameter);
                using (SqlDataAdapter da = new SqlDataAdapter(comm))
                {
                    DataSet dt = new DataSet();
                    da.Fill(dt);//填充
                    return dt.Tables[0];
                }
            }
        }
    }
}

}

hhhvs
hhhvs   2013.08.09 11:48

数据库SQL-SERVER就可以了。
下面是我曾经写的一个数据连接的工具类DBUtil
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace AdoNetTemplet
{
///
/// 数据库访问工具类,通常为singleton
///
public class DBUtil
{

    private  const String CONNSTR = "datasource=.;uid=sa;pwd=sa";

    private static DBUtil instance = null;
    private static Object lockObj = new Object();

    /// <summary>
    /// 私有的构造器
    /// </summary>
    private DBUtil() { }

    //得到工具类的实例
    public static  DBUtil getInstance()
    {
        if (null == instance)
        {
            lock (lockObj)//加锁,使得它是线程安全的
            {
                if (null == instance)
                {
                    instance = new DBUtil();
                }
            }
        }

        return instance;
    }

    //得到一个连接对象
    public SqlConnection getConnection()
    {
         return new SqlConnection(CONNSTR);
    }
    //得到一个sql操作对象
    public SqlCommand getCommand(SqlConnection conn)
    {
        return conn.CreateCommand();
    }

    //关闭资源
    public void free(SqlConnection conn, SqlCommand command)
    {
        if (null == command)
        {
            command.Dispose();
        }

        if (null == conn)
        {
            conn.Dispose();
        }
    }

}

}

//下面是写的增删改查的demo,希望能对你有用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace AdoNetTemplet
{
///
/// 数据库访问层类
///
class Dao
{
private const String CONNSTR = "Data Source=.;Initial Catalog=student;User ID=sa";

    /// <summary>
    /// 添加一个用户对象
    /// </summary>
    /// <param name="user">用户对象</param>
    /// <returns>如果添加成功返回true,否则返回false</returns>
    public Boolean add(User user)
    {
       using(SqlConnection conn = new SqlConnection(CONNSTR))
       {
           conn.Open();
           using (SqlCommand cmd = conn.CreateCommand())
           {
               cmd.CommandText = @"insert into user (username,password,age,gender)
                                values(@username,@password,@age,@gender)";
               cmd.Parameters.Add(new SqlParameter("@username", user.UserName));
               cmd.Parameters.Add(new SqlParameter("@password", user.Password));
               cmd.Parameters.Add(new SqlParameter("@age", user.Age));
               cmd.Parameters.Add(new SqlParameter("@gender", user.Gender));
               return cmd.ExecuteNonQuery()>0;
           }

       }
    }

    /// <summary>
    /// 通过用户Id删除一条记录
    /// </summary>
    /// <param name="userId">用户Id</param>
    /// <returns>如果删除成功返回true,否则返回false</returns>
    public Boolean delete(int userId)
    {
        using (SqlConnection conn = new SqlConnection(CONNSTR))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "delete from user where id=@id";
                cmd.Parameters.Add("@id", userId);
                return cmd.ExecuteNonQuery() > 0;
            }
        }

    }

    /// <summary>
    /// 更新一条记录
    /// </summary>
    /// <param name="user">用户对象</param>
    /// <returns>如果更新成功返回true,否则返回false</returns>
    public Boolean update(User user)
    {
        using (SqlConnection conn = new SqlConnection())
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = @"update user set userName=@username,password=@password,
                                  age=@age,gender=@gender ";
                cmd.Parameters.Add("@username", user.UserName);
                cmd.Parameters.Add("@password", user.Password);
                cmd.Parameters.Add("@age", user.Age);
                cmd.Parameters.Add("@gender", user.Gender);
                return cmd.ExecuteNonQuery() > 0;
            }
        }
    }

    /// <summary>
    /// 根据Id获取一个User对象
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>如果存在满足该ID的用户返回该用户对象,否则返回null</returns>
    public User loadById(int userId)
    {
        using (SqlConnection conn = new SqlConnection(CONNSTR))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "select * from user where id=@id";
                cmd.Parameters.Add(new SqlParameter("@id", userId));
                SqlDataReader reader = cmd.ExecuteReader();
                User user = null;
                if (reader.Read())
                {
                    user = new User();
                    user.UserName = reader.GetString(reader.GetOrdinal("userName"));
                    user.Password = reader.GetString(reader.GetOrdinal("password"));
                    user.Age = reader.GetInt32(reader.GetOrdinal("age"));
                    user.Gender = reader.GetString(reader.GetOrdinal("gender"));
                }

                return user;
            }
        }
    }

    /// <summary>
    /// 获取到所有用户对象
    /// </summary>
    /// <returns>
    /// 如果数据存在用户的记录,将这些记录全部以User对象添加到集合中,并将集合返回;
    /// 如果数据库中没有任何记录,将返回null;
    /// </returns>
    public List<User> getAllUsers()
    {
        using (SqlConnection conn = new SqlConnection(CONNSTR))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "select * from user";
                SqlDataReader reader = cmd.ExecuteReader();
                List<User> users = new List<User>();
                User user;
                while (reader.Read())
                {
                    user = new User();
                    user.UserName = reader.GetString(reader.GetOrdinal("userName"));
                    user.Password = reader.GetString(reader.GetOrdinal("password"));
                    user.Age = reader.GetInt32(reader.GetOrdinal("age"));
                    user.Gender = reader.GetString(reader.GetOrdinal("gender"));
                    users.Add(user);
                }

                return users;
            }
        }
    }
}

}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!