我一直在http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL上关注将我的C#应用程序连接到SQL数据库的教程,但我还不清楚如何从我的MainWindow中实际调用连接。
我已经在我的主程序中实例化了该类的对象,以执行构造函数,但我不确定我的连接是否正在建立,或者如何执行此操作。非常感谢有人指点我正确的方向。
到目前为止我的代码:
DbConnect.cs
namespace SpeedyRent
{
internal class DbConnect
{
private SqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
// Constructor
public DbConnect()
{
Initialize();
}
// Initialize values
private void Initialize()
{
server = "localhost";
database = "rent";
uid = "root";
password = "password123";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new SqlConnection(connectionString);
}
// Open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
// Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CurrentDateTimeTextBlock.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
var dbConnectObject = new DbConnect();
}
}
答案 0 :(得分:1)
我相信您需要的文档位于http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection%28v=vs.110%29.aspx但是为了打开连接,您可以执行dbConnectObject.open();
,然后执行您需要执行的任何操作并使用dbConnectObject.close();