如何将.NET与sql数据库连接?

时间:2009-08-18 07:09:48

标签: sql-server .net-2.0

我目前有Visual Studio 2005和SQL Server 2005.我在SQL Server中安装了一个空数据库,但我不知道如何使用VS连接数据库。

我应该使用什么样的项目(我将在Windows应用程序中使用数据库)以及我将如何将其插入项目并使用它?

编辑:我在Microsoft SQL Server Managament Studio中有一个数据库,我想在winForm中使用它,使用c#。我必须以某种方式连接这两个?

8 个答案:

答案 0 :(得分:4)

您可以创建任一项目类型:

  1. 网络应用程序
  2. Windows应用程序
  3. 控制台应用程序
  4. 网络服务
  5. 班级图书馆
  6. 要连接数据库,请使用以下代码:

    SqlDataReader rdr = null;
    SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
    conn.Open();
    SqlCommand cmd = new SqlCommand("select * from Customers", conn);
    rdr = cmd.ExecuteReader();
    conn.Close();
    conn.Dispose();
    

    我建议你拿一本关于ADO.NET的好书并仔细阅读。您也可以在Google上搜索一些文章。

答案 1 :(得分:2)

试试这个ADO.NET Sample Application

using System;
using System.Data;
using System.Data.OleDb;

class Sample
{
  public static void Main() 
  {
    OleDbConnection nwindConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");

    OleDbCommand catCMD = nwindConn.CreateCommand();
    catCMD.CommandText = "SELECT CategoryID, CategoryName FROM Categories";

    nwindConn.Open();

    OleDbDataReader myReader = catCMD.ExecuteReader();

    while (myReader.Read())
    {
      Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
    }

    myReader.Close();
    nwindConn.Close();
  }
}

再见

答案 2 :(得分:1)

最简单的方法是使用ADO.Net,没有特殊的项目可以使用,只需使用正常的Winforms项目(你说你已经在做)。

以下是您可以关注的一些基础知识http://www.sitepoint.com/article/introduction-ado-net/

答案 3 :(得分:1)

您有几个选项 - 最简单(但性能最差,最理想,或建议企业级使用)是通过Visual Studio中的“服务器资源管理器”。通过View ... Server Explorer ...进行访问,然后展开Data Connections节点,并浏览新创建的数据库。

从这里,您可以将数据源等拖到Windows应用程序上。

但理想情况下,您可以直接使用ADO,存储过程或SQL。

答案 4 :(得分:0)

在visual studio中,您可以使用“数据”菜单选项打开“数据源”视图。添加数据连接并使用向导“定位”数据库。创建表的本地“表示”后,将该表从数据源选项卡拖到窗体应用程序。

查看所有自动创建的对象,并尝试创建对象列表以及它们如何交互。你能发现连接字符串或表定义吗?

答案 5 :(得分:0)

您可能希望考虑nHibernate或类似的ORM。 ORM层不是本机使用ADO.Net,而是有助于减少您正确的重复数据访问代码的容易出错的数量。

学习曲线比跳入ADO.Net要陡峭,但不是很明显,还有很多你需要了解的事情 - 关系,交易和“商业交易”,延迟加载,无论如何你都需要考虑 - 所以我建议被迫考虑它们并不是坏事。

结帐www.nhforge.org了解一些很棒的入门资源。

答案 6 :(得分:0)

public class DbManager
{
    
    public DbManager(string connection)
    {
        conString = connection;
    }

    public string conString, dbname;

    public string GetConnectionString()
    {
        return conString;
    }

    private string ConnectionString
    {
        get
        {
            return GetConnectionString();
        }
    }

    private SqlConnection Connection { get; set; }

    private SqlCommand Command { get; set; }

    public List<DbParameter> OutParameters { get; private set; }

    private void Open()
    {
        try
        {
            Connection = new SqlConnection(ConnectionString);

            Connection.Open();
        }
        catch (Exception ex)
        {
            Close();
        }
    }

    private void Close()
    {
        if (Connection != null)
        {
            Connection.Close();
        }
    }

    // executes stored procedure with DB parameteres if they are passed
    private object ExecuteProcedure(string procedureName, ExecuteType executeType, List<DbParameter> parameters)
    {
        object returnObject = null;

        if (Connection != null)
        {
            if (Connection.State == ConnectionState.Open)
            {
                Command = new SqlCommand(procedureName, Connection);
                Command.CommandType = CommandType.StoredProcedure;

                // pass stored procedure parameters to command
                if (parameters != null)
                {
                    Command.Parameters.Clear();

                    foreach (DbParameter dbParameter in parameters)
                    {
                        System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter();
                        parameter.ParameterName = "@" + dbParameter.Name;
                        parameter.Direction = dbParameter.Direction;
                        parameter.Value = dbParameter.Value;
                        Command.Parameters.Add(parameter);

                    }


                }

                switch (executeType)
                {
                    case ExecuteType.ExecuteReader:
                        SqlDataReader sdr = Command.ExecuteReader();
                        DataTable dt = new DataTable();
                        dt.Load(sdr);
                        returnObject = Command.ExecuteReader();
                        break;
                    case ExecuteType.ExecuteNonQuery:
                        returnObject = Command.ExecuteNonQuery();
                        break;
                    case ExecuteType.ExecuteScalar:
                        returnObject = Command.ExecuteScalar();
                        break;
                    default:
                        break;
                }
            }
        }

        return returnObject;
    }

    // updates output parameters from stored procedure
    private void UpdateOutParameters()
    {
        if (Command.Parameters.Count > 0)
        {
            OutParameters = new List<DbParameter>();
            OutParameters.Clear();

            for (int i = 0; i < Command.Parameters.Count; i++)
            {
                if (Command.Parameters[i].Direction == ParameterDirection.Output)
                {
                    OutParameters.Add(new DbParameter(Command.Parameters[i].ParameterName,
                                                      ParameterDirection.Output,
                                                      Command.Parameters[i].Value));
                }
            }
        }
    }

    // executes scalar query stored procedure without parameters
    public T ExecuteSingle<T>(string procedureName) where T : new()
    {
        return ExecuteSingle<T>(procedureName, null);
    }

    // executes scalar query stored procedure and maps result to single object
    public T ExecuteSingle<T>(string procedureName, List<DbParameter> parameters) where T : new()
    {
        Open();
        IDataReader reader = (IDataReader)ExecuteProcedure(procedureName, ExecuteType.ExecuteReader, parameters);
        T tempObject = new T();

        if (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                PropertyInfo propertyInfo = typeof(T).GetProperty(reader.GetName(i));
                if (propertyInfo != null)
                {
                    if (reader.GetValue(i) == DBNull.Value)
                    {
                        propertyInfo.SetValue(tempObject, null, null);
                    }
                    else
                    {
                        propertyInfo.SetValue(tempObject, reader.GetValue(i), null);
                    }
                }
            }
        }

        reader.Close();

        UpdateOutParameters();

        Close();

        return tempObject;
    }

    // executes list query stored procedure without parameters
    public List<T> ExecuteList<T>(string procedureName) where T : new()
    {
        return ExecuteList<T>(procedureName, null);
    }


    public DataTable ExecuteListTable(string procedureName, List<DbParameter> parameters)
    {
        Open();
        SqlDataReader reader = (SqlDataReader)ExecuteProcedure(procedureName, ExecuteType.ExecuteReader, parameters);
        DataTable dt = new DataTable();
        dt.Load(reader);
        UpdateOutParameters();
        Close();
        return dt;
    }

    // executes list query stored procedure and maps result generic list of objects
    public List<T> ExecuteList<T>(string procedureName, List<DbParameter> parameters) where T : new()
    {
        List<T> objects = new List<T>();

        Open();
        IDataReader reader = (IDataReader)ExecuteProcedure(procedureName, ExecuteType.ExecuteReader, parameters);

        while (reader.Read())
        {
            T tempObject = new T();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                if (reader.GetValue(i) != DBNull.Value)
                {

                
                    PropertyInfo propertyInfo = typeof(T).GetProperty(reader.GetName(i));
                    if (propertyInfo != null)
                    {
                        propertyInfo.SetValue(tempObject, reader.GetValue(i), null);
                    }
                }
            }

            objects.Add(tempObject);
        }

        reader.Close();

        UpdateOutParameters();

        Close();

        return objects;
    }


    // executes non query stored procedure with parameters
    public int ExecuteNonQuery(string procedureName, List<DbParameter> parameters)
    {
        int returnValue;

        Open();

        returnValue = (int)ExecuteProcedure(procedureName, ExecuteType.ExecuteNonQuery, parameters);

        UpdateOutParameters();

        Close();

        return returnValue;
    }
    // executes scaler query stored procedure with parameters
    public string ExecuteScaler(string procedureName, List<DbParameter> parameters)
    {
        string returnValue;

        Open();

        returnValue = Convert.ToString(ExecuteProcedure(procedureName, ExecuteType.ExecuteScalar, parameters));

        UpdateOutParameters();

        Close();

        return returnValue;
    }


    private class SqlParameter
    {
        public SqlParameter()
        {
        }
    }



}

public enum ExecuteType
{
    ExecuteReader,
    ExecuteNonQuery,
    ExecuteScalar
};

public class DbParameter
{
    public string Name { get; set; }
    public ParameterDirection Direction { get; set; }
    public object Value { get; set; }
    public SqlDbType DbType { get; set; }

    public DbParameter(string paramName, ParameterDirection paramDirection, object paramValue)
    {
        Name = paramName;
        Direction = paramDirection;
        Value = paramValue;
    }
    public DbParameter(string paramName, ParameterDirection paramDirection,SqlDbType dbType, object paramValue)
    {
        Name = paramName;
        Direction = paramDirection;
        Value = paramValue;
        dbType = DbType;
    }
}

答案 7 :(得分:0)

var connectionString = _dbContext.Database.GetDbConnection()。ConnectionString;

        DbManager objDbManager = new DbManager(connectionString);
        List<DbParameter> parameters = new List<DbParameter>();
        parameters.Add(new DbParameter("COMPCODE", System.Data.ParameterDirection.Input, compcode));
        parameters.Add(new DbParameter("FROMDT", System.Data.ParameterDirection.Input, fromDt));
        parameters.Add(new DbParameter("TODT", System.Data.ParameterDirection.Input, toDt));
        parameters.Add(new DbParameter("FILTERFROM", System.Data.ParameterDirection.Input, filterFrom));
        
        DataTable dt = objDbManager.ExecuteListTable("PROC_GET_ITEMLIST", parameters);
        List<Tuple<int, string>> results = new List<Tuple<int, string>>();
        foreach (DataRow r in dt.Rows)
        {
            var tup = Tuple.Create((int)r[0], (string)r[1]);
            results.Add(tup);
        }
        return results;