用C#连接到SQL Server

时间:2015-03-07 12:57:58

标签: c# sql-server visual-studio-2010

我是C#的初学程序员。我正在尝试开发一个连接到数据库的应用程序,并执行插入,删除,更新和获取等典型操作。

我收到数据库连接错误。我正在使用SQL Server 2012,我在其中创建了一个名为company的数据库。

这是我的代码:

namespace DAL
{
    public class DAL
    {
        public const string CADENA_CONEXION = "Data Source=localhost;" +
            "Initial Catalog=Company" +
            "Integrated Security=false" +
            "UID=root PWD=root";
        public SqlConnection con;
        public SqlCommand command;

    public DAL()
    {
        con = new SqlConnection();
        con.ConnectionString = CADENA_CONEXION;
    }

    public Boolean addEmployee(Employee emp)
    {
        try
        {
            /*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " + 
           "Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
            string sqlInsertString =
                "INSERT INTO Employee (FirstName, LastName, ID, " +
                "Designation) VALUES (@firstName, @lastName, @ID, @designation)";
            command = new SqlCommand();
            command.Connection.Open();
            command.CommandText = sqlInsertString;

            SqlParameter firstNameparam = new SqlParameter("@firstName", emp.FirstName);
            SqlParameter lastNameparam = new SqlParameter("@lastName", emp.LastName);
            SqlParameter IDparam = new SqlParameter("@ID", emp.EmpCode);
            SqlParameter designationParam = new SqlParameter("@designation", emp.Designation);

            command.Parameters.AddRange(new SqlParameter[]{
            firstNameparam,lastNameparam,IDparam,designationParam});

            command.ExecuteNonQuery();
            command.Connection.Close();
            return true;
        }
        catch (Exception ex)
        {
            return false;
            throw;
        }

        return true;
    }
}

错误是什么?我在这一行得到例外:

command.Connection.Open();

提前致谢

3 个答案:

答案 0 :(得分:0)

SqlConnection con = new SqlConnection("Your Connection String Goes here");

您应该像这样

分配与SqlCommand对象的连接
SqlCommand command = new SqlCommand();
command.Connection = con;

  SqlCommand command = new SqlCommand("YourQuery",con);

执行命令的一些重要步骤

  

1:创建SqlConnection对象并为该对象分配连接字符串

SqlConnection con = new SqlConnection("Your Connection String Goes here");

SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
  

2:创建SqlCommand对象并为该对象提供命令文本(您的查询)和连接字符串

SqlCommand command = new SqlCommand("Select * from Products",con);

SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";

您还可以指定CommandType

command.CommandType =CommandType.Text; 
/* if you are executing storedprocedure CommandType Will be
  => CommandType.StoredProcedure; */

然后你可以像这样执行命令

 try 
 {
  con.Open();
  int TotalRowsAffected = command.ExecuteNonQuery();
 }
 catch(Exeception ex)
 {
   MessageBox.Show(ex.Message);
 }
 finaly
 {
  con.Close();
 } 

答案 1 :(得分:0)

没有初始化sqlcommand连接,初始化的方法是:

command.Connection=con;

这是完整的代码:

namespace DAL
{
    public class DAL
    {
        public const string CADENA_CONEXION = "Data Source=localhost;" +
            "Initial Catalog=Company" +
            "Integrated Security=false" +
            "UID=root PWD=root";
        public SqlConnection con;
        public SqlCommand command;

    public DAL()
    {
        con = new SqlConnection();
        con.ConnectionString = CADENA_CONEXION;
    }

    public Boolean addEmployee(Employee emp)
    {
        try
        {
            /*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " + 
           "Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
            string sqlInsertString =
                "INSERT INTO Employee (FirstName, LastName, ID, " +
                "Designation) VALUES (@firstName, @lastName, @ID, @designation)";
            command = new SqlCommand();
            command.Connection=con;
            command.Connection.Open();
            command.CommandText = sqlInsertString;

            SqlParameter firstNameparam = new SqlParameter("@firstName", emp.FirstName);
            SqlParameter lastNameparam = new SqlParameter("@lastName", emp.LastName);
            SqlParameter IDparam = new SqlParameter("@ID", emp.EmpCode);
            SqlParameter designationParam = new SqlParameter("@designation", emp.Designation);

            command.Parameters.AddRange(new SqlParameter[]{
            firstNameparam,lastNameparam,IDparam,designationParam});

            command.ExecuteNonQuery();
            command.Connection.Close();
            return true;
        }
        catch (Exception ex)
        {
            return false;
            throw;
        }

        return true;
    }
}

答案 2 :(得分:0)

只是一个FYI:try finally块的替代方法,它确保数据库连接关闭是使用using语句,如:

using (SqlConnection connection = new SqlConnection(
       connectionString))
{
    try
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
    catch (InvalidOperationException)
    {
        //log and/or rethrow or ignore
    }
    catch (SqlException)
    {
        //log and/or rethrow or ignore
    }
    catch (ArgumentException)
    {
        //log and/or rethrow or ignore
    }
}

请参阅此处的SqlCommand类的MSDN文档https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx,并查找ExecuteNonQuery()方法,该方法用于执行INSERT,UPDATE和DELETE语句。然后查找可用于执行返回单个值的SELECT语句的ExecuteScalar()方法。您可以使用ExecuteReader()为返回多列的SELECT语句返回SqlDataReader。