// Create DB method public static void DBCreate() { if (File.Exists(DBFileName)) { Console.WriteLine("BD file is already exists. No need to create "); } else { Console.WriteLine("DB file does not exist. Creating a DB file"); ADOX.Catalog cat = new ADOX.Catalog(); try { // Name and source of MDB file cat.Create("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" + DBLocationPath + DBFileName); // Source=D:\\db_graph.mdb or other location Console.WriteLine("BDCreate succeeded! "); } catch (System.Runtime.InteropServices.COMException Ex) { Console.WriteLine("BDCreate error: " + Ex); cat = null; } DBConnect(); DBStructCreate(); } }
private bool createDB() { bool isres = false; ADOX.Catalog cat = new ADOX.Catalog(); try { dbName = getDBName(); pathToDb = txtPathToDB.Text + $@"{dbName}"; connString = $@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={pathToDb}; Jet OLEDB:Engine Type=5"; cat.Create(connString); OleDbConnection con = cat.ActiveConnection as OleDbConnection; if (con != null) { con.Close(); } isres = true; } catch (Exception ex) { MessageBox.Show(ex.Message); isres = false; } cat = null; return(isres); }
//Creates the db in ->...\source\repos\Company\Company\bin\Debug public Boolean CreateDB() { Boolean result = false; try { ADOX.Catalog cat = new ADOX.Catalog(); String File = "Master.mdb"; cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + File + ";" + "Jet OLEDB:Engine Type=5"); MessageBox.Show("Database Created Successfully ...\\source\\repos\\Company\\Company\\bin\\Debug"); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Master.mdb"); con.Open(); string strTemp = " [Id] Number, [FirstName] Text, [LastName] Text, [BirthDate] Text "; OleDbCommand com = new OleDbCommand(); com.Connection = con; com.CommandText = "CREATE TABLE Employees(" + strTemp + ")"; com.ExecuteNonQuery(); com.Connection.Close(); con.Close(); cat = null; result = true; }catch (Exception ex) { result = false; } return(result); }
private void napravi_novu_datoteku(object sender, EventArgs e) { Save.ShowDialog(); cur_open_file = Save.FileName + ".tocke"; this.Text = cur_open_file; try { ADOX.Catalog cat = new ADOX.Catalog(); cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); cat = null; System.IO.File.Copy(dbpath, cur_open_file, true); } catch (Exception ee) { if (ee.ToString() != "1") { if (Debug) { MessageBox.Show("Spremi staru datoteku"); } spremiKaoToolStripMenuItem.PerformClick(); File.Delete(dbpath); ADOX.Catalog cat = new ADOX.Catalog(); cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); cat = null; System.IO.File.Copy(dbpath, cur_open_file, true); } } Osvjezi.PerformClick(); }
public bool CreateDatabase() { bool result = false; ADOX.Catalog cat = new ADOX.Catalog(); try { string connection = this.GetConnectionString(); cat.Create(connection); Table assignment = this.CreateAssignmentTable(cat); cat.Tables.Append(assignment); Table folders = this.CreateFoldersTable(cat); cat.Tables.Append(folders); Table image = this.CreateImageTable(cat); cat.Tables.Append(image); //Now Close the database ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; if (con != null) { con.Close(); } result = true; } catch (Exception ex) { result = false; } cat = null; return(result); }
public void DtaDbCre() { if (!File.Exists(@"Data\Data.accdb")) { ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table table = new ADOX.Table(); try { cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Data\\Data.accdb; Jet OLEDB:Engine Type=5"); //Now Close the database ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; if (con != null) { con.Close(); } //result = true; } catch //(Exception ex) { } cat = null; TblCre(); } //End if } //End dbCre
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static bool CreateNewAccessDatabase(string fileName) { bool result = false; ADOX.Catalog cat = new ADOX.Catalog(); //ADOX.Table table = new ADOX.Table(); //Create the table and it's fields. //table.Name = "Table1"; //table.Columns.Append("Field1"); //table.Columns.Append("Field2"); try { cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5"); //cat.Tables.Append(table); //Now Close the database ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; if (con != null) { con.Close(); } result = true; } catch (Exception) { result = false; } cat = null; return(result); }
public void Creat() { string app_path; app_path = Application.StartupPath + "\\Manager.mdb"; ADOX.Catalog catalog = new ADOX.Catalog(); catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + app_path + ";Jet OLEDB:Engine Type=5"); }
static void Main(string[] args) { string username = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); if (File.Exists(username + @"\Documents\H.T I.R Aide\Notes\NewMDB.accdb")) { File.Delete(username + @"\Documents\H.T I.R Aide\Notes\NewMDB.accdb"); } ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table table = new ADOX.Table(); table.Name = "Overview"; table.Columns.Append("Offense Type"); table.Columns.Append("Total Notes"); table.Columns.Append("Percent of Notes"); table.Columns.Append("Number tagged as Closed"); DataTable test = new DataTable(); test.NewRow(); DataColumn column; DataRow row; column = new DataColumn(); column.ColumnName = "id"; test.Columns.Add(column); column = new DataColumn(); column.ColumnName = "hi"; test.Columns.Add(column); ArrayList hi = new ArrayList(); for (int i = 0; i < 10; i++) { row = test.NewRow(); row["id"] = i; row["hi"] = i + 1; test.Rows.Add(row); hi.Add(row["id"] + " " + row["hi"]); WriteLine(row["id"] + " " + row["hi"]); } string[] nope = new string [hi.Count]; hi.CopyTo(nope); File.WriteAllLines(username + @"\Documents\H.T I.R Aide\Notes\testNewMDB.accdb", nope); cat.Create("Provider =Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + username + @"\Documents\H.T I.R Aide\Notes\NewMDB.accdb; " + "Jet OLEDB:Engine Type=5"); cat.Tables.Append(table); WriteLine("Database Created Successfully"); ReadKey(); cat = null; }
//创建数据库 public void createDb(String versionNum) { ADOX.Catalog catalog = new ADOX.Catalog(); //String versionNum = extension.Text; try { catalog.Create(databaseCon + otherDbs + versionNum + ".mdb" + ";Jet OLEDB:Engine Type=5"); } catch { } ADODB.Connection cn = new ADODB.Connection(); cn.Open(databaseCon + otherDbs + versionNum + ".mdb", null, null, -1); catalog.ActiveConnection = cn; //创建表 ADOX.Table table = new ADOX.Table(); table.Name = "config1"; //创建列 ADOX.Column column = new ADOX.Column(); column.ParentCatalog = catalog; column.Name = "ID"; column.Type = DataTypeEnum.adInteger; column.DefinedSize = 9; column.Properties["AutoIncrement"].Value = true; table.Columns.Append(column, DataTypeEnum.adInteger, 9); // 设置为主键 table.Keys.Append("FirstTablePrimaryKey", KeyTypeEnum.adKeyPrimary, column, null, null); table.Columns.Append("fileName", DataTypeEnum.adVarWChar, 0); table.Columns.Append("fileSize", DataTypeEnum.adInteger, 0); table.Columns.Append("createTime", DataTypeEnum.adDate, 0); table.Columns.Append("modifiedTime", DataTypeEnum.adDate, 0); table.Columns.Append("path", DataTypeEnum.adLongVarWChar, 0); table.Columns.Append("versionNum", DataTypeEnum.adInteger, 0); table.Columns.Append("updateMethod", DataTypeEnum.adVarWChar, 0); try { // 添加表 catalog.Tables.Append(table); } catch (Exception ex) { MessageBox.Show(ex.Message); } //此处一定要关闭连接,否则添加数据时候会出错 table = null; catalog = null; //Application.DoEvents(); cn.Close(); }
//tests public static void RunAdoxAdorTest() { try { ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table tab = new ADOX.Table(); _msg.Length = 0; _msg.Append("RunAdoxAdorTest started ..."); Program._messageLog.WriteLine(_msg.ToString()); tab.Name = "TestTab1"; tab.Columns.Append("PK1", ADOX.DataTypeEnum.adInteger); tab.Columns.Append("F1", ADOX.DataTypeEnum.adVarWChar, 30); tab.Columns.Append("F2", ADOX.DataTypeEnum.adDouble); tab.Columns.Append("F3", ADOX.DataTypeEnum.adVarBinary); tab.Columns.Append("F4", ADOX.DataTypeEnum.adBoolean); tab.Columns.Append("F5", ADOX.DataTypeEnum.adCurrency); tab.Columns.Append("F6", ADOX.DataTypeEnum.adWChar); tab.Columns.Append("F7", ADOX.DataTypeEnum.adSmallInt); tab.Columns.Append("F8", ADOX.DataTypeEnum.adSingle); //tab.Columns.Append("F9", ADOX.DataTypeEnum.adDecimal,18); //invalid, use double instead tab.Columns.Append("F9", ADOX.DataTypeEnum.adLongVarBinary); tab.Columns.Append("F10", ADOX.DataTypeEnum.adLongVarWChar); tab.Columns.Append("F11", ADOX.DataTypeEnum.adBoolean); tab.Columns.Append("F12", ADOX.DataTypeEnum.adVarWChar, 1); tab.Columns.Append("F13", ADOX.DataTypeEnum.adUnsignedTinyInt); tab.Columns.Append("F14", ADOX.DataTypeEnum.adDate); //if (File.Exists(@"C:\Testfiles\Access\NewMDB.mdb")) // File.Delete(@"C:\Testfiles\Access\NewMDB.mdb"); //cat.Create(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Testfiles\Access\NewMDB.mdb;User Id=admin;Password=;Jet OLEDB:Engine Type=5"); if (File.Exists(@"C:\Testfiles\Access\NewMDB.accdb")) { File.Delete(@"C:\Testfiles\Access\NewMDB.accdb"); } cat.Create(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Testfiles\Access\NewMDB.accdb;User Id=admin;Password=;Jet OLEDB:Engine Type=6"); cat.Tables.Append(tab); } catch (System.Exception ex) { _msg.Length = 0; _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex)); Program._messageLog.WriteLine(_msg.ToString()); AppMessages.DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog); } finally { _msg.Length = 0; _msg.Append("... RunAdoxAdorTest finished."); Program._messageLog.WriteLine(_msg.ToString()); } }
public string CreateDb() { ADOX.Catalog cat = new ADOX.Catalog(); string tempFile = Path.GetTempFileName(); File.Delete(tempFile); cat.Create(BuildQueryString(tempFile)); cat.ActiveConnection.Close(); return(tempFile); }
private void otvori_dat(object sender, EventArgs e) { if (sender.ToString() == "Otvori") { Open.ShowDialog(); cur_open_file = Open.FileName; System.IO.File.Copy(cur_open_file, dbpath, true); this.Text = cur_open_file; } //MessageBox.Show(Open.FileName + "\n\n" + Application.StartupPath); if (!File.Exists(dbpath)) { ADOX.Catalog cat = new ADOX.Catalog(); cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); cat = null; } conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); //adapter.Fill(medataset); try { using (OleDbCommand cmd = new OleDbCommand(global::Interpolator.Properties.Resources.PropertiesCreateString, conn)) { conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } catch (Exception ee) { if (Debug) { MessageBox.Show("Error: " + ee.ToString()); } } medataset = new DataSet(); OleDbCommand cmd1 = new OleDbCommand(selekt, conn); adapter = new OleDbDataAdapter(cmd1); adapter.Fill(medataset); for (int i = 0; i < this.Controls.Count; i++) { if (this.Controls[i].GetType().ToString() == "System.Windows.Forms.Panel" && this.Controls[i].Name != "SkupFunkcija") { this.Controls[i].Dispose(); i--; } } br_tablica = 0; updatezy(); }
public bool CreateDatabaseFile() { if (this.DirectoryExists()) { var cat = new ADOX.Catalog(); cat.Create(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", this.CompleteFileString())); cat = null; } return false; }
} // end InsertOrderItem public static void ConstructDatabase() { // Microsoft advise that ADOX class is not tested. It is used here only to create a database ADOX.Catalog cat = new ADOX.Catalog(); // Create Database if it does not exists if (!File.Exists(dbFolder + "BurgerDB.mdb")) { cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dbFolder + "BurgerDB.mdb;" + "Jet OLEDB:Engine Type=5"); MessageBox.Show("Database Created Successfully"); } else { MessageBox.Show("Database already exists at " + dbFolder); } // Create tables conn.Open(); // Do not use possible SQL keywords in table names, field names. // OleDbCommand cmd1 = new OleDbCommand("CREATE TABLE test1 (Name varchar(50), Quantity integer)", conn); // works string cmdString = " CREATE TABLE OrderItem (Name varchar(50), TypeName varchar(50), ISize varchar(10), BaseCost decimal, Quantity int)"; // + OleDbCommand cmd1 = new OleDbCommand(cmdString, conn); try // Ceeate the database table if it does not exist { // Now lets execute the SQL ;D cmd1.ExecuteNonQuery(); } catch (Exception e) { MessageBox.Show(e.Message); } // Insert data to table // InsertOrderItem(conn, out cmdString, out cmd1); conn.Close(); cat = null; } // end of ConstructDatabase
/// <summary> /// 创建数据库 /// </summary> public void creatDataDB() { if (!File.Exists(filePath)) //如果数据库不存在,那就添加数据库 { try { catalog.Create(connection); } catch (Exception ex) { Console.WriteLine("error:" + ex); } } }
/// <summary> /// 动态创建ACCESS /// </summary> /// <returns></returns> public bool CreateAccess() { try { ADOX.Catalog catalog = new ADOX.Catalog(); catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DbPath + ";Jet OLEDB:Engine Type=5"); return(true); } catch (Exception ex) { _strErrorInfo = ex.Message; return(false); } }
/// <summary> /// Создание Базы данных /// </summary> public static void add() { try { ADOX.Catalog k = new ADOX.Catalog(); k.Create("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\\BD\\New_BD_mass1.mdb"); MessageBox.Show("БД Создана"); } catch (System.Runtime.InteropServices.COMException sit) { MessageBox.Show(sit.Message); } }
/// <summary> /// Creating mdb file /// </summary> /// <param name="filename">the name of file</param> private static void CreateAccessDatabase(string filename) { string path = Directory.GetCurrentDirectory(); if (!Directory.Exists(Directory.GetCurrentDirectory())) Directory.CreateDirectory(path); ADOX.Catalog database = new ADOX.Catalog(); try { database.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + @"\" + filename + ".mdb; Jet OLEDB:Engine Type=5"); } catch (Exception e) { MessageBox.Show(e.Message); } database = null; }
}// end of function public void MDBCreate() { string DBPath; DBPath = "C:\\Users\\CaptiveIT1\\Documents\\Temp\\MC.mdb"; // create DB via ADOX if not exists if (!System.IO.File.Exists(DBPath)) { //DeleteMDB(); //if (System.IO.File.Exists(DBPath + "\\MC.mdb")) //System.IO.File.Delete(DBPath + "\\MC.mdb"); ADOX.Catalog cat = new ADOX.Catalog(); cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBPath); //cat = null; } } // end of function
public Boolean CreateAccessDatabase() { bool result = false; ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table table = new ADOX.Table(); //Create the table and it's fields. table.Name = "UserInfo"; table.Columns.Append("username", ADOX.DataTypeEnum.adVarWChar, 40); table.Columns.Append("password", ADOX.DataTypeEnum.adVarWChar, 40); table.Columns.Append("age", ADOX.DataTypeEnum.adInteger, 2); table.Columns.Append("gender", ADOX.DataTypeEnum.adVarWChar, 6); table.Columns.Append("occupation", ADOX.DataTypeEnum.adVarWChar, 40); table.Columns.Append("income", ADOX.DataTypeEnum.adDouble, 10); table.Keys.Append("Primary Key", ADOX.KeyTypeEnum.adKeyPrimary, "password", "", ""); try { cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=C:\Users\Umer\Documents\Visual Studio 2015\Projects\masterpage\" + "UserInfo.mdb" + "; Jet OLEDB:Engine Type=5"); //cat.Columns.Append("col1", DataTypeEnum.adInteger, 4); cat.Tables.Append(table); //Now Close the database ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; if (con != null) { con.Close(); } result = true; } catch (Exception ex) { Console.WriteLine(ex); // Namebox.Text = ex.ToString(); result = false; } cat = null; return(result); }
static void CreateNewDatabase() { ADOX.Catalog cat = new ADOX.Catalog(); string tmpStr; string filename = @"C:\LocalDatabase.accdb"; tmpStr = "Provider=Microsoft.Jet.OLEDB.4.0;"; tmpStr += "Data Source=" + filename + ";Jet OLEDB:Engine Type=5"; cat.Create(tmpStr); Table table = new Table(); table.Name = "Main"; table.Columns.Append("NObjednavky", ADOX.DataTypeEnum.adInteger); table.Columns.Append("STAV", ADOX.DataTypeEnum.adBoolean); table.Columns.Append("Cena", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Dobirka", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Firma", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Jmeno", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Adresa", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("PSC", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Mesto", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Vaha", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Sluzby", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("V_symbol", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Telefon", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Email", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Doprava", ADOX.DataTypeEnum.adVarWChar); table.Columns.Append("Vzkaz", ADOX.DataTypeEnum.adLongVarWChar); cat.Tables.Append(table); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(table); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.Tables); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat); cat = null; }
private void Init() { ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table customersTable = new ADOX.Table(); customersTable.Name = "customers"; customersTable.Columns.Append("customerId", ADOX.DataTypeEnum.adVarWChar, 255); customersTable.Columns.Append("customerName", ADOX.DataTypeEnum.adVarWChar, 255); customersTable.Columns.Append("flightId", ADOX.DataTypeEnum.adVarWChar, 255); ADOX.Table flightsTable = new ADOX.Table(); flightsTable.Name = "flights"; flightsTable.Columns.Append("flightId", ADOX.DataTypeEnum.adVarWChar, 255); flightsTable.Columns.Append("airlineCompany", ADOX.DataTypeEnum.adVarWChar, 255); flightsTable.Columns.Append("origin", ADOX.DataTypeEnum.adVarWChar, 255); flightsTable.Columns.Append("destination", ADOX.DataTypeEnum.adVarWChar, 255); flightsTable.Columns.Append("flightDate", ADOX.DataTypeEnum.adVarWChar, 255); cat.Create(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSource); cat.Tables.Append(customersTable); cat.Tables.Append(flightsTable); }
public static bool ExportAccessDb(String fileName, DataSet ds) { bool result = false; ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table table = new ADOX.Table(); try { cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5"); //create tables for (int i = 0; i < ds.Tables.Count; i++) { var ctTable = ds.Tables[i]; //Create the table and it's fields. table.Name = ctTable.TableName; CreateAccessCols(table, ctTable); cat.Tables.Append(table); }//end method //now close the database ADODB.Connection conn = cat.ActiveConnection as ADODB.Connection; if (conn != null) conn.Close(); result = true; } catch (Exception ex) { result = false; } cat = null; FillAccessDb(fileName, ds); return result; }//end method
void Timer1Tick(object sender, EventArgs e) { timer1.Stop(); //остановка таймера //определяем расположение программы (путь) ClassConfig.Rapid_ProgramPath = Environment.CurrentDirectory + "\\"; //расположение папки ресурсов ClassConfig.Rapid_Resource = ClassConfig.Rapid_ProgramPath + "resource"; //Проверка существования папки if(!Directory.Exists(ClassConfig.Rapid_Resource)){ //папки нет, она будет создана заново Directory.CreateDirectory(ClassConfig.Rapid_Resource); } //поиск локальной базы данный (список серверов) ClassConfig.Rapid_FileListBase = ClassConfig.Rapid_Resource + "\\list.mdb"; if(!File.Exists(ClassConfig.Rapid_FileListBase)){ //файл не найден, он будет создан ADOX.Catalog ADOXCatalog = new ADOX.Catalog(); try{ ADOXCatalog.Create(ClassConfig.ConnectLineBegin + ClassConfig.Rapid_FileListBase + ClassConfig.ConnectLineEnd + ClassConfig.ConnectPass); //Создание базы данных и таблицы подключений. OleDbConnection OleDb_Connection = new OleDbConnection(); OleDbCommand OleDb_Command; String SQLFullCommand = ""; String SQLCommand = ""; OleDb_Connection.ConnectionString = ClassConfig.ConnectLineBegin + ClassConfig.Rapid_FileListBase + ClassConfig.ConnectLineEnd + ClassConfig.ConnectPass; OleDb_Connection.Open(); //соединение с базой //Создаем таблицу SQLCommand = "CREATE TABLE ListBase ([ID_ListBase] COUNTER PRIMARY KEY, "; SQLFullCommand += SQLCommand; SQLCommand = "[Name] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Server] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[DataBase] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Uid] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Pwd] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Admin] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Client] VARCHAR DEFAULT " + "\"" + "\"" + ")"; SQLFullCommand += SQLCommand; OleDb_Command = new OleDbCommand(SQLFullCommand, OleDb_Connection); OleDb_Command.ExecuteNonQuery(); //выполнение запроса //создание первой записи по умолчению для локального сервера SQLFullCommand = "INSERT INTO ListBase ([Name], [Server], [DataBase], [Uid], [Pwd], [Admin], [Client]) VALUES ('Информационная база №1', 'localhost', 'rapid', 'root', '', 'http://localhost/rapid.com/Admin/', 'http://localhost/rapid.com')"; OleDb_Command = new OleDbCommand(SQLFullCommand, OleDb_Connection); OleDb_Command.ExecuteNonQuery(); //выполнение запроса //отключение соединения OleDb_Connection.Close(); }catch(Exception ex){ MessageBox.Show(ex.ToString()); //Сообщение об ошибке Application.Exit(); } } //-------------------------------------------- //Открытие окна выбора конфигурации ClassForms.Rapid_SelectLoad = new FormSelectLoad(); ClassForms.Rapid_SelectLoad.Show(); //-------------------------------------------- Visible = false; //главная форма становится невидимой }
void Timer1Tick(object sender, EventArgs e) { timer1.Stop(); //остановка таймера //определяем расположение программы (путь) ClassConfig.Rapid_ProgramPath = Environment.CurrentDirectory + "\\"; //расположение папки ресурсов ClassConfig.Rapid_Resource = ClassConfig.Rapid_ProgramPath + "resource"; //Проверка существования папки if (!Directory.Exists(ClassConfig.Rapid_Resource)) { //папки нет, она будет создана заново Directory.CreateDirectory(ClassConfig.Rapid_Resource); } //поиск локальной базы данный (список серверов) ClassConfig.Rapid_FileListBase = ClassConfig.Rapid_Resource + "\\list.mdb"; if (!File.Exists(ClassConfig.Rapid_FileListBase)) { //файл не найден, он будет создан ADOX.Catalog ADOXCatalog = new ADOX.Catalog(); try{ ADOXCatalog.Create(ClassConfig.ConnectLineBegin + ClassConfig.Rapid_FileListBase + ClassConfig.ConnectLineEnd + ClassConfig.ConnectPass); //Создание базы данных и таблицы подключений. OleDbConnection OleDb_Connection = new OleDbConnection(); OleDbCommand OleDb_Command; String SQLFullCommand = ""; String SQLCommand = ""; OleDb_Connection.ConnectionString = ClassConfig.ConnectLineBegin + ClassConfig.Rapid_FileListBase + ClassConfig.ConnectLineEnd + ClassConfig.ConnectPass; OleDb_Connection.Open(); //соединение с базой //Создаем таблицу SQLCommand = "CREATE TABLE ListBase ([ID_ListBase] COUNTER PRIMARY KEY, "; SQLFullCommand += SQLCommand; SQLCommand = "[Name] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Server] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[DataBase] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Uid] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Pwd] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Admin] VARCHAR DEFAULT " + "\"" + "\"" + ", "; SQLFullCommand += SQLCommand; SQLCommand = "[Client] VARCHAR DEFAULT " + "\"" + "\"" + ")"; SQLFullCommand += SQLCommand; OleDb_Command = new OleDbCommand(SQLFullCommand, OleDb_Connection); OleDb_Command.ExecuteNonQuery(); //выполнение запроса //создание первой записи по умолчению для локального сервера SQLFullCommand = "INSERT INTO ListBase ([Name], [Server], [DataBase], [Uid], [Pwd], [Admin], [Client]) VALUES ('Информационная база №1', 'localhost\\SQLEXPRESS', 'rapid', 'sa', '0000', '', '')"; OleDb_Command = new OleDbCommand(SQLFullCommand, OleDb_Connection); OleDb_Command.ExecuteNonQuery(); //выполнение запроса //отключение соединения OleDb_Connection.Close(); }catch (Exception ex) { MessageBox.Show(ex.ToString()); //Сообщение об ошибке Application.Exit(); } } //-------------------------------------------- //Открытие окна выбора конфигурации ClassForms.Rapid_SelectLoad = new FormSelectLoad(); ClassForms.Rapid_SelectLoad.Show(); //-------------------------------------------- Visible = false; //главная форма становится невидимой }
//static void CreateOleDbCommand(string query1, string CONNECT_STRING) //{ // using (OleDbConnection connection = new OleDbConnection(CONNECT_STRING)) // { // OleDbCommand cmd1 = new OleDbCommand(query1, connection); // cmd1.Connection.Open(); // cmd1.ExecuteNonQuery(); // cmd1.Connection.Close(); // } //} static void Main(string[] args) { OleDbConnection connection = new OleDbConnection(CONNECT_STRING); OleDbCommand command1 = new OleDbCommand("CREATE TABLE TablesStopReason(intStopReason AUTOINCREMENT PRIMARY KEY, strReason string, bitDowntime bit, bitUnscheduled bit, bitPMStoppages bit, bitScheduledRepairsAndOther bit, intLocationId int NOT NULL)", connection); OleDbCommand command2 = new OleDbCommand("CREATE TABLE TablesManufacturer(intManufacturerID AUTOINCREMENT PRIMARY KEY, strManufactName string)", connection); OleDbCommand command3 = new OleDbCommand("CREATE TABLE TablesModel(intModelID AUTOINCREMENT PRIMARY KEY, strName string, intSMCSFamilyID int, strImage string, intManufacturerID int)", connection); if (File.Exists("Database.mdb")) { try { connection.Open(); Console.WriteLine("Connection opened"); command1.ExecuteNonQuery(); command2.ExecuteNonQuery(); command3.ExecuteNonQuery(); } catch (Exception exc) { Console.WriteLine(exc.Message); } finally { connection.Close(); connection.Dispose(); Console.WriteLine("Connection closed"); if (command1 != null) { command1.Dispose(); } if (command2 != null) { command2.Dispose(); } if (command3 != null) { command3.Dispose(); } } } else { ADOX.Catalog catalog = new ADOX.Catalog(); catalog.Create(CONNECT_STRING); } Console.WriteLine("Какую операцию вы хотите выполнить? 1 - внесение данных в таблицу, 2 - просмотр данных в таблицах, 3 - удаление записи в таблицах"); int selectInt = Convert.ToInt32(Console.ReadLine()); if (selectInt == 1) { InsertCommand(); } else if (selectInt == 2) { SelectCommand(); } else if (selectInt == 3) { } }
public string usingDB(string inDataSet) { connection.Close(); engine.Initialize(); engine.Evaluate("library(readxl)"); engine.Evaluate("dataset <- read_excel(\"" + inDataSet + "\")"); DataFrame dataset = engine.Evaluate("dataset").AsDataFrame(); string conStr = ""; string pathFull = tmpFolder + "FullBD.accdb"; conStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + pathFull + ";"; if (File.Exists(pathFull)) { File.Delete(pathFull); } connection.ConnectionString = conStr; ADOX.Catalog cat = new ADOX.Catalog(); cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + pathFull + ";"); Table fTable = new Table(); fTable.Name = "Full"; for (int i = 0; i < numVars; i++) { fTable.Columns.Append(nameVars[i], DataTypeEnum.adDouble); } cat.Tables.Append(fTable); cat = null; connection.Close(); connection.Open(); OleDbCommand commandUpd = connection.CreateCommand(); string textQuery = "INSERT INTO [Full] ("; for (int i = 0; i < numVars; i++) { textQuery += nameVars[i] + ','; } textQuery = textQuery.Substring(0, textQuery.Length - 1) + ") VALUES ("; for (int i = 0; i < numRecords; i++) { string subQuery = ""; for (int j = 0; j < numVars; j++) { if (!double.IsNaN((double)(dataset[i, j]))) { subQuery += dataset[i, j].ToString() + ","; } else { subQuery += "0 ,"; } } subQuery = subQuery.Substring(0, subQuery.Length - 1) + ")"; commandUpd.CommandText = textQuery + subQuery; commandUpd.ExecuteNonQuery(); } connection.Close(); conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathFull; connection.ConnectionString = conStr; connection.Open(); OleDbCommand command = connection.CreateCommand(); textQuery = "SELECT COUNT(*) FROM [Full]"; command.CommandText = textQuery; string res = Convert.ToString(command.ExecuteScalar()); connection.Close(); return(res); }
public Form1() { CheckForIllegalCrossThreadCalls = false; p = new Postavke(); p.Show(); p.Hide(); graf = new prikaz_tocki(p); th = new Thread(graf.poc); //var obj = new WindowsFormsApplication1.SimpleWindow(); //new Thread(obj.poc).Start(); InitializeComponent(); number_of_controls_without_funcs = this.Controls.Count; dbpath = Application.StartupPath + global::Interpolator.Properties.Resources.NameOfDbString; if (!File.Exists(dbpath)) { ADOX.Catalog cat = new ADOX.Catalog(); try { cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); } catch (Exception e) { if (Debug) { MessageBox.Show(e.ToString()); } } cat = null; } else { ADOX.Catalog cat = new ADOX.Catalog(); System.IO.File.Delete(dbpath); cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); } conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbpath); //adapter.Fill(medataset); try { using (OleDbCommand cmd = new OleDbCommand(global::Interpolator.Properties.Resources.PropertiesCreateString, conn)) { conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } catch (Exception ee) { if (Debug) { MessageBox.Show("Error: " + ee.ToString()); } } medataset = new DataSet(); OleDbCommand cmd1 = new OleDbCommand(selekt, conn); adapter = new OleDbDataAdapter(cmd1); adapter.Fill(medataset); updatezy(); }
private void CreateDBtablesColumn() { try { string ConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", Environment.CurrentDirectory + "\\Table\\StudentsDB.mdb"); ADOX.Catalog cat = new ADOX.Catalog(); ADOX.Table locTable = new ADOX.Table(); ADOX.Key locKey = new ADOX.Key(); ADOX.Column locCol = new Column(); //Create the Locations table and it's fields locTable.Name = "Результати"; locCol.Name = "id"; //locCol.Attributes = ColumnAttributesEnum.adColNullable; locCol.Type = ADOX.DataTypeEnum.adInteger; locTable.Columns.Append(locCol); locTable.Columns.Append("Учбовий квиток", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Курс", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Імя", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Прізвище", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("По батькові", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Дата народження", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Стать", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Вік", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Зріст", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Вага", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТС0", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТС1", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТС2", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТС3", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТС4", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТС5", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТД0", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТД1", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТД2", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТД3", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТД4", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("АТД5", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("ЧСС0", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("ЧСС1", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("ЧСС2", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("ЧСС3", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("ЧСС4", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("ЧСС5", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Cl", DataTypeEnum.adVarWChar, 255); locTable.Columns.Append("Dist", DataTypeEnum.adVarWChar, 255); locKey.Name = "Primary Key"; locKey.Columns.Append("id"); locKey.Type = KeyTypeEnum.adKeyPrimary; cat.Create(ConnectionString); // Must create database file before applying autonumber to column locCol.ParentCatalog = cat; if (locCol.Name != "id") { locCol.Attributes = ColumnAttributesEnum.adColFixed; //locCol.Attributes = ColumnAttributesEnum.adColNullable; } locCol.Properties["AutoIncrement"].Value = true; //Exception triggered here cat.Tables.Append(locTable); } catch { MessageBox.Show("Не вдається свторити Базу даних.\nДані не збережено!"); } }
private void button2_Click(object sender, EventArgs e) { if (ds != null && tblnm != null && tblnm != "" && tblnm != " ") { SaveFileDialog a = new SaveFileDialog(); a.Filter = "Access Database File (*.accdb)|*.accdb|All files (*.*)|*.*"; if (a.ShowDialog() == DialogResult.OK) { String saveFilenm = a.FileName.ToString(); ADOX.Catalog cat = new ADOX.Catalog(); try { Thread thread = new Thread(() => { try { cat.Create(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + saveFilenm); connetionString1 = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + saveFilenm + ";Jet OLEDB:Database Password=Pass123;"; oledbCnn1 = new OleDbConnection(connetionString1); oledbCnn1.Open(); String strQury = "create table `" + tblnm + "` ("; String col = "", para = ""; int i1; for (i1 = 0; i1 < totalTxtGen + 1; i1++) { if (i1 == totalTxtGen) { col += "`" + textBox[i1].Name + "` TEXT "; } else { col += "`" + textBox[i1].Name + "` TEXT ,"; } para += "@" + textBox[i1].Name + "~"; } //para += "@" + textBox[i1].Name + "~"; strQury += col + " )"; strQury = strQury.Replace('.', ' '); OleDbCommand cmd = new OleDbCommand(strQury, oledbCnn1); cmd.ExecuteNonQuery(); String[] p = para.Split('~'); String tmp1 = "insert into `" + tblnm + "` ("; for (int i = 0; i < (p.Length - 1); i++) { if (i == p.Length - 2) { tmp1 += "`" + p[i].Replace('@', ' ').Trim() + "` "; } else { tmp1 += "`" + p[i].Replace('@', ' ').Trim() + "` ,"; } } tmp1 += ") VALUES ("; for (int i = 0; i < (p.Length - 1); i++) { if (i == p.Length - 2) { tmp1 += "`" + p[i] + "`"; } else { tmp1 += "`" + p[i] + "` ,"; } } tmp1 += ")"; if (oledbCnn.State == ConnectionState.Closed) { oledbCnn.Open(); } cmd = new OleDbCommand(getQry(), oledbCnn); OleDbDataReader dr = cmd.ExecuteReader(); OleDbCommand cmd1 = new OleDbCommand(tmp1, oledbCnn1); while (dr.Read()) { cmd1.Parameters.Clear(); for (int co = 0; co < p.Length - 1; co++) { cmd1.Parameters.AddWithValue(p[co] + "", dr.GetValue(co).ToString()); } cmd1.ExecuteNonQuery(); } cmd1.Dispose(); oledbCnn1.Close(); MessageBox.Show("File Saved.."); } catch (System.Runtime.InteropServices.COMException x) { MessageBox.Show(x + ""); } finally { Invoke(new Action(() => { x.Close(); })); } }); thread.Start(); x = new Form2(); x.ShowDialog(); } catch (Exception x) { MessageBox.Show("" + x); } } else { MessageBox.Show("Please Open Database First."); } } else { MessageBox.Show("Please Open Database First."); } }
private void button1_Click(object sender, EventArgs e) { String db_name = "NEWDB.accdb"; String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data" + @" Source=C:\PBloodTestManager\" + db_name; //Create the Database try { ADOX.Catalog cat = new ADOX.Catalog(); cat.Create(connectionString); //Now Close the database ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; if (con != null) con.Close(); MessageBox.Show("Database '" + db_name + "' Created"); } catch (Exception) { MessageBox.Show("Database already exists"); } String tableName = "NEW_TABLE"; String createSQL = "CREATE TABLE " + tableName + "(" + "SNo Integer PRIMARY KEY," + "TestDate Date," + " Glucose Double," + " Cholesterol Double," + " LDL Double," + " HDL Double," + " Triglycerides Double," + " Fibrinogen Double," + " HemoglobinA1C Double," + " DHEA Double," + " PSA Double," + " Homocysteine Double," + " CRP Double," + " TSH Double," + " Testosterone Double," + " Estradiol Double" + ")"; OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand dbCmd = new OleDbCommand(); try { conn.Open(); //MessageBox.Show(createSQL); dbCmd.Connection = conn; dbCmd.CommandText = createSQL; dbCmd.ExecuteNonQuery(); MessageBox.Show("Table Created"); } catch (OleDbException exp) { MessageBox.Show("Database Error:" + exp.Message.ToString()); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } }
}// end of function public void CreateTable(string _batch) { string DBPath; OleDbConnection conn; //OleDbDataAdapter adapter; //DataTable dtMain; DBPath = Application.StartupPath + "\\" + _batch + ".mdb"; //// create DB via ADOX if not exists if (!File.Exists(DBPath)) { ADOX.Catalog cat = new ADOX.Catalog(); cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBPath); cat = null; } // connect to DB conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBPath); conn.Open(); // create table "Table_1" if not exists // DO NOT USE SPACES IN TABLE AND COLUMNS NAMES TO PREVENT TROUBLES WITH SAVING, USE _ // OLEDBCOMMANDBUILDER DON'T SUPPORT COLUMNS NAMES WITH SPACES try { using (OleDbCommand cmd = new OleDbCommand("CREATE TABLE [InputFile_Temp] ([BRSTN] TEXT, " + " [AccountNumber] TEXT, [RT1to5] TEXT, [RT6to9] TEXT,[AccountNumberWithHyphen] TEXT," + "[Serial] TEXT, [Name1] TEXT, [Name2] TEXT " + ",[Address1] TEXT, [Address2] TEXT, [Address3] TEXT,[Address4] TEXT, [Address5] TEXT," + "[Address6] TEXT, [BankName] TEXT,[StartingSerial] TEXT,[EndingSerial] TEXT, [PcsPerBook] TEXT,[FileName] TEXT,[PageNumber] NUMBER, [DataNumber] TEXT);", conn)) { cmd.ExecuteNonQuery(); } using (OleDbCommand cmd = new OleDbCommand("CREATE TABLE [InputFile_1outs] ([BRSTN] TEXT, " + " [AccountNumber] TEXT, [RT1to5] TEXT, [RT6to9] TEXT,[AccountNumberWithHyphen] TEXT," + "[Serial] TEXT, [Name1] TEXT, [Name2] TEXT " + ",[Address1] TEXT, [Address2] TEXT, [Address3] TEXT,[Address4] TEXT, [Address5] TEXT," + "[Address6] TEXT, [BankName] TEXT,[StartingSerial] TEXT,[EndingSerial] TEXT, [PcsPerBook] TEXT,[FileName] TEXT,[PageNumber] NUMBER, [DataNumber] TEXT);", conn)) { cmd.ExecuteNonQuery(); } using (OleDbCommand cmd = new OleDbCommand("CREATE TABLE [InputFile_2outs] ([BRSTN] TEXT, " + " [AccountNumber] TEXT, [RT1to5] TEXT, [RT6to9] TEXT,[AccountNumberWithHyphen] TEXT," + "[Serial] TEXT, [Name1] TEXT, [Name2] TEXT " + ",[Address1] TEXT, [Address2] TEXT, [Address3] TEXT,[Address4] TEXT, [Address5] TEXT," + "[Address6] TEXT, [BankName] TEXT,[StartingSerial] TEXT,[EndingSerial] TEXT, [PcsPerBook] TEXT,[FileName] TEXT,[PageNumber] NUMBER, [DataNumber] TEXT);", conn)) { cmd.ExecuteNonQuery(); } using (OleDbCommand cmd = new OleDbCommand("CREATE TABLE [InputFile_3outs] ([BRSTN] TEXT, " + " [AccountNumber] TEXT, [RT1to5] TEXT, [RT6to9] TEXT,[AccountNumberWithHyphen] TEXT," + "[Serial] TEXT, [Name1] TEXT, [Name2] TEXT " + ",[Address1] TEXT, [Address2] TEXT, [Address3] TEXT,[Address4] TEXT, [Address5] TEXT," + "[Address6] TEXT, [BankName] TEXT,[StartingSerial] TEXT,[EndingSerial] TEXT, [PcsPerBook] TEXT,[FileName] TEXT,[PageNumber] NUMBER, [DataNumber] TEXT);", conn)) { cmd.ExecuteNonQuery(); } using (OleDbCommand cmd = new OleDbCommand("CREATE TABLE [InputFile_4outs] ([BRSTN] TEXT, " + " [AccountNumber] TEXT, [RT1to5] TEXT, [RT6to9] TEXT,[AccountNumberWithHyphen] TEXT," + "[Serial] TEXT, [Name1] TEXT, [Name2] TEXT " + ",[Address1] TEXT, [Address2] TEXT, [Address3] TEXT,[Address4] TEXT, [Address5] TEXT," + "[Address6] TEXT, [BankName] TEXT,[StartingSerial] TEXT,[EndingSerial] TEXT, [PcsPerBook] TEXT,[FileName] TEXT,[PageNumber] NUMBER, [DataNumber] TEXT);", conn)) { cmd.ExecuteNonQuery(); } conn.Close(); } catch (Exception ex) { if (ex != null) { ex = null; } } }// end of function
private void createDatabaseTableToolStripMenuItem_Click(object sender, EventArgs e) { String db_name = "NEWDB.accdb"; String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data" + @" Source=C:\PBloodTestManager\" + db_name; //Create the Database try { ADOX.Catalog cat = new ADOX.Catalog(); cat.Create(connectionString); //Now Close the database ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; if (con != null) { con.Close(); } MessageBox.Show("Database '" + db_name + "' Created in C:\\PBloodTestManager\\"); } catch (Exception) { MessageBox.Show("Database already exists"); } String tableName = "NEW_TABLE"; String createSQL = "CREATE TABLE " + tableName + "(" + "SNo Integer PRIMARY KEY," + "TestDate Date," + " Glucose Double," + " Cholesterol Double," + " LDL Double," + " HDL Double," + " Triglycerides Double," + " Fibrinogen Double," + " HemoglobinA1C Double," + " DHEA Double," + " PSA Double," + " Homocysteine Double," + " CRP Double," + " TSH Double," + " Testosterone Double," + " Estradiol Double" + ")"; OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand dbCmd = new OleDbCommand(); try { conn.Open(); //MessageBox.Show(createSQL); dbCmd.Connection = conn; dbCmd.CommandText = createSQL; dbCmd.ExecuteNonQuery(); MessageBox.Show("Table NEW_TABLE Created"); } catch (OleDbException exp) { MessageBox.Show("Database Error:" + exp.Message.ToString()); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } }