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

发布于 2024-08-02 08:08:14 字数 248 浏览 4 评论 0原文

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

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

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

I currently have Visual Studio 2005 and SQL Server 2005. I have installed an empty database into SQL Server, but I don't have any idea how to use VS to connect with the database.

What kind of project should I use (I'm going to use the database in a windows application) and exactly how will I be able to insert it to the project and use it?

EDIT: I have a database in Microsoft SQL Server Managament Studio, and I want to use it in a winForm, using c#. I have to connect these two somehow ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

左耳近心 2024-08-09 08:08:14

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

  1. Web 应用程序
  2. Windows 应用程序
  3. 控制台应用程序
  4. Web 服务
  5. 类库

要连接到数据库,请使用下面的代码:

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 的好书并通读它。你也可以在谷歌上搜索一些文章。

You can create either of the project type:

  1. Web Application
  2. Windows Application
  3. Console Application
  4. Web Service
  5. Class Library

To connect to database, use the code below:

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();

I suggest you pick up a good book on ADO.NET and read through it. You could search for some articles on Google too.

那小子欠揍 2024-08-09 08:08:14

试试这个 ADO.NET 示例应用程序

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();
  }
}

再见

try this 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();
  }
}

bye

奈何桥上唱咆哮 2024-08-09 08:08:14

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

以下是您可以遵循的一些基础知识 http://www.sitepoint.com/article /简介-ado-net/

The simplest way is using ADO.Net , there is no special project to use , just use a normal Winforms Project (which you said you are already doing).

Here are some basics that you can follow http://www.sitepoint.com/article/introduction-ado-net/

深爱成瘾 2024-08-09 08:08:14

您有几个选择 - 最简单的(但性能最低、理想或推荐用于企业规模使用)是通过 Visual Studio 中的“服务器资源管理器”。通过查看...服务器资源管理器...进行访问并展开数据连接节点,然后浏览新创建的数据库。

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

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

You've a few options - the easiest (but least performant, ideal, or recommended for enterprise-scale use) is via the 'Server Explorer' in Visual Studio. Accessing via View...Server Explorer... and expand Data Connections node, and browse your newly created database.

From here you can drag data sources etc onto your Windows Application.

Ideally however you'd use ADO, stored procedure or SQL directly.

橘和柠 2024-08-09 08:08:14

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

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

In visual studio you got a Data menu option that can open a Data Sources view. Add a data connection and use the wizard to 'target' the database. After creating a local 'representation' of a table, drag that table from the datasource tab to you windows form application.

Look at all the automatically created objects and try to create a list of objects and how they interact. Can you spot the connectionstring or the table definition?

戈亓 2024-08-09 08:08:14

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

学习曲线比跳入 ADO.Net 更陡峭,但并不明显,并且您需要学习很多东西 - 关系、事务和“业务事务”、延迟加载,无论如何您都需要考虑 - 所以我表明被迫思考它们并不是坏事。

查看 www.nhforge.org 获取一些很棒的入门资源。

You may wish to consider nHibernate or a similiar ORM. Rather than using ADO.Net natively, the ORM layer can help reduce the amount of error prone an repetitive data access code that you right.

The learning curve is steeper than jumping into ADO.Net, but not significantly, and lots of the things you will need to learn about - relations, transactions and "business transactions", lazy loading, you will need to think about anyway - so I would suggest that being forced to think about them is no bad thing.

Checkout www.nhforge.org for some great getting started resources.

漫漫岁月 2024-08-09 08:08:14
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;
    }
}
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;
    }
}
天涯离梦残月幽梦 2024-08-09 08:08:14

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;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文