C# 在C中连接到SQL Server
我是一个C语言的初学者。我正在尝试开发一个连接到数据库的应用程序,并执行诸如插入、删除、更新和获取之类的典型操作 数据库连接出错。我正在使用SQL Server 2012,在那里我创建了一个名为company的数据库 这是我的代码:C# 在C中连接到SQL Server,c#,sql-server,visual-studio-2010,C#,Sql Server,Visual Studio 2010,我是一个C语言的初学者。我正在尝试开发一个连接到数据库的应用程序,并执行诸如插入、删除、更新和获取之类的典型操作 数据库连接出错。我正在使用SQL Server 2012,在那里我创建了一个名为company的数据库 这是我的代码: namespace DAL { public class DAL { public const string CADENA_CONEXION = "Data Source=localhost;" + "Init
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();
提前谢谢
SqlConnection con = new SqlConnection("Your Connection String Goes here");
您应该像这样将连接分配给SqlCommand对象
SqlCommand command = new SqlCommand();
command.Connection = con;
或
执行命令的一些重要步骤
1:创建SqlConnection对象并为该对象分配连接字符串
或
2:创建SqlCommand对象,并将您的查询和连接字符串分配给该对象
或
您还可以指定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();
}
不初始化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;
}
}
仅供参考:确保数据库连接关闭的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文档,并查找用于执行INSERT、UPDATE和DELETE语句的方法。然后查找可用于执行返回单个值的SELECT语句的方法。您可以使用为返回多列的SELECT语句返回SqlDataReader。异常消息是什么?当我看到您的连接字符串时,就好像您想连接到Mysql数据库而不是SQL Server数据库,您能给出更多说明吗先打开连接,然后创建命令并将连接分配给命令!!command.Connection.Open将失败并出现NullReferenceException,因为您尚未将SqlConnection对象分配给该命令的Connection属性,但您正在尝试对其调用Open。您编写的所有更改我都已完成。现在,我得到这个异常消息:用户的init会话错误=“”使用这个连接字符串:public const string CADENA_CONEXION=Data Source=localhost;+初始目录=公司+集成安全=真;我已修改了连接字符串,但收到了相同的消息例外请检查连接字符串中的主机名例如:sql server管理中的FATHI-PC是的,这方面有错误。我解决了,但问题是一样的。我也有同样的例外。
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();
}
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;
}
}
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
}
}