我已经使用Visual Studio创建了一个数据库,我正在使用Windows身份验证连接到该数据库。
我尝试了很多事情,但是没有用
namespace Stock
{
public partial class Fm_principal : Form
{
public SqlConnection connexion_BDD()
{
//Connection base de donnée
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Trusted_Connection=false";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
return connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return connection;
}
}
public Fm_principal()
{
InitializeComponent();
}
private void cb_test_Click(object sender, EventArgs e)
{
connexion_BDD();
string request = "SELECT ref_pdt FROM produits";
SqlCommand command = new SqlCommand(request, connexion_BDD());
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
cb_test.Items.Add(dataReader["ref_pdt"]);
}
}
}
}
由于当前连接已关闭,因此dataReader出现错误
答案 0 :(得分:0)
我从字面上敲了一下,但您会想要这样的东西:(提示:像Dapper一样看一下,您可能会更喜欢)
public partial class Fm_principal : Form
{
public SqlConnection connexion_BDD()
{
//Connection base de donnée
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Trusted_Connection=true";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
return connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return connection;
}
}
public Fm_principal()
{
InitializeComponent();
}
private void cb_test_Click(object sender, EventArgs e)
{
using (var connection = connection_BDD())
{
string request = "SELECT ref_pdt FROM produits";
using (var command = new SqlCommand(request, connection))
{
using (var dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
cb_test.Items.Add(dataReader["ref_pdt"]);
}
}
}
}
}
}
编辑:以防万一我误解了您的问题,以表示您确实要使用用户名和密码进行连接,然后将连接字符串设置为:
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;User Id=YOURUSERNAME;Password=YOURPASSWORD;Trusted_Connection=false";
编辑:设置SQL凭据(我不建议这样做,因为我认为集成安全性会更好,因为它可以避免用户名/密码凭据泄漏到源代码管理中)