初めてデータベース プログラミングを行うので、Access でデータベースを作成して、それを使って何かをしようとしました。私が作成したデータベースはデスクトップ上で「TestDatabase」と呼ばれ、このデータベース内に作成したテーブルは「TestTable」と呼ばれます。そして、ここに私のコードがあります:
using System;
using System.Data;
using System.Data.SqlClient;
namespace DatabaseTest
{
class Test
{
static void Main(string[] args)
{
// I don't know if my connection is correct or not. My access database is on my local desktop though
string connectionString = "Data Source = (local); Initial Catalog = TestDatabase; Integrated Security = SSPI";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataReader reader = null;
SqlCommand command = new SqlCommand("SELECT * from TestTable", connection);
connection.Open();
try
{
reader = command.ExecuteReader();
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.ToString());
}
// print all the data in the table
while (reader.Read())
{
Console.Write(reader[0].ToString() + ", ");
Console.Write(reader[1].ToString() + ", ");
Console.Write(reader[2].ToString() + ", ");
Console.Write(reader[3].ToString() + ", ");
Console.WriteLine(reader[4].ToString());
}
}
Console.ReadLine();
}
}
}
そして、これが私のテーブルのようです。
ID First Name Last Name Age Friend
1 Leon Ma 18 Yes
2 Amy Jane 16 No
3 David Zhang 20 No
4 Alan Yue 19 Yes
ただし、コンソールに何も表示されないため、機能しません。私は何を間違えましたか。本当に助けが必要です。ありがとう。