第一次做数据库编程,所以我只是在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
但是,它不起作用,因为我的控制台上什么也没有出现。我做错什么了。真的需要一些帮助。谢谢。