using System;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;
using System.IO;
using ADODB;
using ADOX;
namespace DB
{
class AccessDBUtil
{
private static string fileName = "";
static string str_url = "";
private static String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_url;
private AccessDBUtil()
{
}
//判断数据库是否存在,如果不存在则创建数据库
public static void checkDBExists()
{
if (!File.Exists(str_url))
{
Catalog catalog = new Catalog();
try
{
catalog.Create(connectionString);
//连接数据库
ADODB.Connection cn = new ADODB.Connection();
cn.Open(connectionString, null, null, -1);
catalog.ActiveConnection = cn;
CreateParaOpDB(catalog,"tableName");
catalog = null;
cn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
}
private static void CreateParaOpDB(Catalog catalog,string tableName)
{
Table table = new Table();
table.Name = tableName;
Column column = new Column();
column.ParentCatalog = catalog;
column.Type = ADOX.DataTypeEnum.adInteger; // 必须先设置字段类型
column.Name = "ID";
column.DefinedSize = 8;
column.Properties["AutoIncrement"].Value = true;
table.Columns.Append(column, ADOX.DataTypeEnum.adInteger, 0);
table.Columns.Append("Num", ADOX.DataTypeEnum.adVarWChar, 120);
table.Columns.Append("DateTime", ADOX.DataTypeEnum.adVarWChar, 120);
try
{
catalog.Tables.Append(table);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
//此处一定要关闭连接,否则添加数据时候会出错
table = null;
Application.DoEvents();
}
public static DataSet ExecuteQuery(string sql)
{
return ExecuteQuery(sql, null);
}
//执行查询语句,返回dataset
public static DataSet ExecuteQuery(string sql, OleDbParameter[] parameters)
{
//Debug.WriteLine(sql);
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, connection);
if (parameters != null) da.SelectCommand.Parameters.AddRange(parameters);
da.Fill(ds, "ds");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return ds;
}
}
public static int ExecuteInsert(string sql)
{
return ExecuteInsert(sql, null);
}
//执行单条插入语句,并返回id,不需要返回id的用ExceuteNonQuery执行。
public static int ExecuteInsert(string sql, OleDbParameter[] parameters)
{
Console.WriteLine(sql);
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand(sql, connection);
try
{
connection.Open();
if (parameters != null) cmd.Parameters.AddRange(parameters);
cmd.ExecuteNonQuery();
cmd.CommandText = @"select @@identity";
int value = Int32.Parse(cmd.ExecuteScalar().ToString());
return value;
}
catch (Exception e)
{
Console.WriteLine(ex);
throw e;
}
}
}
}
}
Access
最新推荐文章于 2024-09-03 09:04:15 发布