简体   繁体   English

Delphi - 在运行时创建 MySQL 数据库

[英]Delphi - Creating MySQL database at runtime

I have a delphi application which connects to MySQL database, however, I would like to give create an easy way for my end user to implement the MySQL database.我有一个连接到 MySQL 数据库的 delphi 应用程序,但是,我想为我的最终用户创建一个简单的方法来实现 MySQL 数据库。 I thought about creating a button within my application which the user could press to delete any current instances of the scehma, and create a new schema with the correct tables and columns which my application requires to function.我想在我的应用程序中创建一个按钮,用户可以按下它来删除 scehma 的任何当前实例,并使用我的应用程序运行所需的正确表和列创建一个新模式。

I have written the code to create the new database.我已经编写了创建新数据库的代码。 It is as follows:如下:

CREATE SCHEMA IF NOT EXISTS fakeschema;   
USE fakeschema;  
CREATE TABLE table1  
(IDtable1 int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,  
Line1 varchar(45),  
Line2 varchar(45));  

The code functions correctly within MySQL, however I am receiving an SQL Syntax error when executing the code.代码在 MySQL 中正常运行,但是我在执行代码时收到 SQL 语法错误。 I am getting of:我得到:

error in your SQL syntax near 'USE fakeschema; 'USE fakeschema; 附近的 SQL 语法错误; CREATE TABLE table1 (IDtable1 int(11) PRIMARY KEY NO' CREATE TABLE table1 (IDtable1 int(11) PRIMARY KEY NO'

I am using an ADOConnection to link to the datasource.我正在使用ADOConnection链接到数据源。 I am writing the connection string once the button has been pressed.按下按钮后,我正在编写连接字符串。 I am using an ADOQuery to execute the SQL code.我正在使用ADOQuery来执行 SQL 代码。

Here is a snippet of the code which I am using to connect to the database:这是我用来连接到数据库的代码片段:

ADOC.ConnectionString := 'PROVIDER = MSDASQL; DRIVER={MySQL ODBC 3.51 Driver};
SERVER=localhost; Data Source=faketest; DATABASE=fakeschema; USER ID=root;
PASSWORD=pass; OPTION=3;';
ADOC.DefaultDatabase := 'fakeschema';  
ADOC.Connected := True;  

Am I using the wrong tools/methods?我是否使用了错误的工具/方法? I am new to MySQL and I am currently learning Delphi.我是 MySQL 的新手,目前正在学习 Delphi。

As mentioned in one of my comments, the issue is trying to execute multiple individual SQL statements in a single TAdoQuery component.正如我在评论中提到的,问题是试图在单个 TAdoQuery 组件中执行多个单独的SQL 语句。

In an ideal world, you would have a component such as MyDAC which has a script component you could use in place of the TAdoQuery (MyDAC would give you other benefits too such as not having to connect via ODBC).在理想的世界中,您将拥有一个诸如 MyDAC 之类的组件,其中包含一个脚本组件,您可以使用它来代替 TAdoQuery(MyDAC 还会为您带来其他好处,例如不必通过 ODBC 进行连接)。 I don't know if there any free MySQL components out there which have a scripting component.我不知道是否有任何免费的 MySQL 组件具有脚本组件。

Another approach is you could create a script file (eg createFakeSchema.sql) and execute it through the command line.另一种方法是您可以创建一个脚本文件(例如 createFakeSchema.sql)并通过命令行执行它。 eg:例如:

createFakeSchema.sql: createFakeSchema.sql:

CREATE SCHEMA IF NOT EXISTS fakeschema;   
USE fakeschema;  
CREATE TABLE table1  
(IDtable1 int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,  
Line1 varchar(45),  
Line2 varchar(45));

and example source code:和示例源代码:

procedure TfrmMain.DoExecuteScriptFile;
var
  cmd: string;
  KeepOpen: Boolean;
begin
  KeepOpen := True;

  // option to automatically close window once execution is done
  // for releasing you would not want it kept open, but handy for debugging
  if KeepOpen then
    cmd := '/k '
  else
    cmd := '/c ';

  cmd := cmd + Format(' mysql -uroot -proot -D%s < "%s"', ['FakeSchema', 'createFakeSchema.sql']);
  ShellExecute(handle,'open', 'cmd.exe', Pchar(cmd), nil, SW_SHOW );
end;

This way you can create your script file externally somewhere, test it through MySQL yourself then when you know your script is working, you can run it through your program.这样你就可以在外部的某个地方创建你的脚本文件,自己通过 MySQL 测试它,然后当你知道你的脚本正在工作时,你可以通过你的程序运行它。 If you want to hide the command window while executing change the SW_SHOW in ShellExecute to SW_HIDE.如果要在执行时隐藏命令窗口,请将 ShellExecute 中的 SW_SHOW 更改为 SW_HIDE。 This way you don't even need any components at all - just have mysql.exe accessible in the path or include the full path in the cmd statement.这样,您甚至根本不需要任何组件 - 只需在路径中访问 mysql.exe 或在 cmd 语句中包含完整路径。

This was done in MySQL 5.1, so hopefully works for 3.5...这是在 MySQL 5.1 中完成的,所以希望适用于 3.5 ...

If you look at the documentation for MySQL 3.x, and scroll waaay down the page on CREATE TABLE , you'll see an example in one of the comment posts of what appears to be the proper syntax.如果您查看 MySQL 3.x 的文档,并在CREATE TABLE上向下滚动页面,您将在其中一个评论帖子中看到一个示例,说明似乎是正确的语法。 It appears to be more like this (untested, of course):它似乎更像这样(当然未经测试):

CREATE TABLE IF NOT EXISTS Table1 (
  IDtable1 int(11) NOT NULL AUTO_INCREMENT,  
  Line1 varchar(45),  
  Line2 varchar(45)
  PRIMARY KEY (IDTable1)
);

Here's another example I found at DevArticles这是我在DevArticles 上找到的另一个例子

CREATE TABLE `articles` (
  `aID` int(4) NOT NULL auto_increment,
  `auth` varchar(100) NOT NULL default '',
  `title` varchar(100) NOT NULL default '',
  `article_body` text NOT NULL,
  `date_published` date NOT NULL default '0000-00-00',
  PRIMARY KEY  (`aID`)
) 

You might want to reconsider your strategy, though.不过,您可能需要重新考虑您的策略。 If the user accidentally clicks the Reset Database button and deletes all of their data , this may cause you some issues (possibly legal ones, depending on where you live and what data is involved).如果用户不小心点击了Reset Database按钮并删除了他们的所有数据,这可能会给您带来一些问题(可能是合法的,取决于您住的地方和涉及的数据)。 :-) :-)

It might be better to think of backing up the data and then do a TRUNCATE of the tables instead, where you could restore from the backup if something went wrong.最好考虑备份数据,然后对表执行TRUNCATE ,如果出现问题,您可以从备份中恢复。 This would allow re-use of the existing schema.这将允许重新使用现有模式。

If you ever receive a MySQL error message like如果您收到过类似的 MySQL 错误消息

error in your SQL syntax near ' (quoted) ' ' (quoted) '附近的 SQL 语法错误

you always have to look at the code that is before that quoted part.您总是必须查看引用部分之前的代码。

In this special case CREATE SCHEMA IF NOT EXISTS fakeschema;在这种特殊情况下CREATE SCHEMA IF NOT EXISTS fakeschema;

The documentation is also very clear about that 文档对此也非常清楚

CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2 .从 MySQL 5.0.2 开始, CREATE SCHEMA 是 CREATE DATABASE 的同义词。

So you cannot use this synonym , because your MySQL server (version below 5.0.2) or in this case the ODBC driver did not know this.所以你不能使用这个同义词,因为你的 MySQL 服务器(版本低于 5.0.2)或者在这种情况下 OD​​BC 驱动程序不知道这一点。

This should get rid of the current error message这应该摆脱当前的错误消息

CREATE DATABASE IF NOT EXISTS fakeschema;   
USE fakeschema;  
CREATE TABLE table1(
  IDtable1 int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,  
  Line1    varchar(45),  
  Line2    varchar(45)
);  

A solution (based on @Jason 's) that does not involves cmd.exe is to use mysql source command:不涉及 cmd.exe 的解决方案(基于@Jason 的)是使用 mysql source命令:

cmd := '-u USER_NAME -pUSER_PASSWORD DB_NAME -e "source createFakeSchema.sql"';
ShellExecute(handle, 'open', 'mysql.exe', Pchar(cmd), 'PATH_TO_MYSQL', SW_SHOW);

I did a hard job to find how to create a database.我很难找到如何创建数据库。 I'm using "Zeos":我正在使用“Zeos”:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ShellAPI, ZAbstractConnection, ZConnection, DB,
  ZAbstractRODataset, ZAbstractDataset, ZDataset;

type
  TForm1 = class(TForm)
    btn1: TButton;
    ZConnection1: TZConnection;
    ZQuery: TZQuery;
    btn2: TButton;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
begin
  ZConnection1.Protocol := 'mysql-5';
  ZConnection1.Database := '';
  ZConnection1.User := 'root';
  ZConnection1.Password := 'root';
  ZConnection1.Connect;
end;

procedure TForm1.btn2Click(Sender: TObject);
var
  vSQL : string;
begin
  ZQuery.Close;
  ZQuery.SQL.Clear;
  vSQL := 'CREATE DATABASE IF NOT EXISTS `test`';
  ZQuery.SQL.Add(vSQL);
  ZQuery.ExecSQL;
end;

end.

I hope that I can help anyone;我希望我可以帮助任何人;

Best Regards最好的祝福

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM