我正在使用遗传算法项目"时间表Scedualing" 使用C#和Sql server ..
我将项目划分为3层(数据访问层,业务层和接口)
数据访问层包含:
(构造函数初始化连接对象,打开连接的方法,打开连接的方法,从数据库读取数据的方法,从数据库中插入,更新,删除数据的方法)
例如:
//从数据库中插入,更新,删除数据的方法
public void ExecuteCommand(string stored_procedure, SqlParameter[] param)
{
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = stored_procedure;
sqlcmd.Connection = sqlconnection;
if (param != null)
{
sqlcmd.Parameters.AddRange(param);
}
sqlcmd.ExecuteNonQuery();
}
业务层包含每个表单的类
例如:ADD_PROF.class for" Add Professor Form"
....................
现在从数据库获取有关教授的所有数据,我创建(GET_ALL_PROF)程序并将此代码写入ADD_PROF类
public DataTable GET_ALL_PROF() //copied and pasted down for verfing
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DataTable Dt = new DataTable();
Dt = DAL.SelectData("GET_ALL_PROF", null);
DAL.Close();
return Dt;
}
我的问题是......我不知道如何从数据库中的教授表中获取(教授ID)并将其放入变量中以将其传递给遗传算法代码IN C#?
sql中的过程是
Create proc [dbo].[get_id_PROF]
as
select ID_PROF from [dbo].[PROFESSOR]
答案 0 :(得分:3)
您可以使用SqlDataReader
从数据库中读取数据,只需使用它将数据库中的数据存储在变量中。
int professorId;
private static void ReadOrderData(string connectionString)
{
string queryString = "select ID_ST from [dbo].[PROFESSOR];";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Call Read before accessing data.
if (reader.HasRows())
{
reader.Read();
professorId = reader.GetInt32(0);
// Call Close when done reading.
reader.Close();
}
}
}
}
或者您可以尝试使用存储过程:
int professorId;
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Data is accessible through the DataReader object here.
reader.Read();
professorId = reader.GetInt32(0);
}
}