开发者

how to connect Microsoft Access Database to visual c#?

how to onnect Microsoft Access Database to visual c#

for example: i开发者_StackOverflow社区 make a database that have a table named "student" and fields " id , name " so i make a c# form that have 2 text boxs and a button "add" that add the contents of the two text box to the database

bye


Here's an overview of the process on MSDN you might take a look at. Don't hesitate to ask if you encounter some specific problem implementing the solution.


You will also need to have MDAC (Microsoft Data Access Components).

In order to help you with the connection string and its parameters for a data file such as an Access database, please follow the following link specific to Access: Access.

For other connection strings in general: ConnectionStrings.com.

In short, you need to specify your complet filename to the Access database file in your connectionString.

using (OleDBConnection connection = new OleDBConnection(connectiongString)) {
    if (connection.State != ConnectionState.Open)
        connection.Open();

    string sql = "INSERT INTO Student (Id, Name) VALUES (@idParameter, @nameParameter)"

    using (OleDBCommand command = connection.CreateCommand()) {
        command.CommandText = sql;
        command.CommandType = CommandType.Text;

        OleDBParameter idParameter = command.CreateParameter()
        idParameter.DbType = System.Int32;
        idParameter.Direction = Parameterdirection.Input;
        idParameter.Name = "@idParameter";
        idParameter.Value = studentId; // Where studentId is an int variable that holds your parsed TextBox.Text property value.

        OleDBParameter nameParameter = command.CreateParameter()
        // Do the same as you did above for the nameParameter.

        try {
            command.ExecuteNonQuery()
        } finally {
            command.Dispose();
            connection.Dispose();
        }
    }
}

Disclaimer This code is provided as-is as it was not compiled nor tested. That is only to show you the idea of how it works. Further tests might be necessary depending on your project architecture or else.


You can use the ado.net database connection objects from within the System.Data.OleDb namespace. These object include the following

OleDbConnection OleDbCommand OleDbDataReader

Additionally, here is the quick tutorial from Microsoft to get you up and running.

Enjoy!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜