GVKun编程网logo

Access MySQL from C (用 C 访问 MySQL 数据库)(c语言访问mysql)

25

如果您对AccessMySQLfromC感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于AccessMySQLfromC的详细内容,我们还将为您解答用C访问MySQL数据库的

如果您对Access MySQL from C 感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Access MySQL from C 的详细内容,我们还将为您解答用 C 访问 MySQL 数据库的相关问题,并且为您提供关于.net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式、access mysql mssql 随机 10条数据的sql语句 原创、Access 数据导入mysql_MySQL、ACCESS数据库向MySQL快速迁移小程序(一)_MySQL的有价值信息。

本文目录一览:

Access MySQL from C (用 C 访问 MySQL 数据库)(c语言访问mysql)

Access MySQL from C (用 C 访问 MySQL 数据库)(c语言访问mysql)

This blog is mainly a collection of study notes and some simple tryout examples. For more details, refer to "Beginning Linux Programming", Chapter 8.

 

Most Commonly Used APIs for Accessing MySQL:

MYSQL *mysql_init(MYSQL *);

MYSQL *mysql_real_connect(MYSQL *connection,

const char *server_host,

const char *sql_user_name,

const char *sql_password,

const char *db_name,

unsigned int port_number,

const char *unix_socket_name,

unsigned int flags);

void mysql_close(MYSQL *connection);

int mysql_options(MYSQL *connection, enum option_to_set,

const char *argument);

int mysql_query(MYSQL *connection, const char *query);

my_ulonglong mysql_affected_rows(MYSQL *connection);

unsigned int mysql_errno(MYSQL *connection);

char *mysql_error(MYSQL *connection);

MYSQL_RES *mysql_store_result(MYSQL *connection);

my_ulonglong mysql_num_rows(MYSQL_RES *result);

MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);	

void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset);

MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result);

MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset);

void mysql_free_result(MYSQL_RES *result);

unsigned int mysql_field_count(MYSQL *connection);

MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result);

char *mysql_get_client_info(void);

char *mysql_get_host_info(MYSQL *connection);

char *mysql_get_server_info(MYSQL *connection);

char *mysql_info(MYSQL *connection);

int mysql_select_db(MYSQL *connection, const char *dbname);

int mysql_shutdown(MYSQL *connection, enum mysql_enum_shutdown_level);

 

Example1: how to connect to a mysql server

#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"

int main(int argc, char *argv[])
{
        MYSQL *conn_ptr;

        conn_ptr = mysql_init(NULL);
	if (!conn_ptr)
	{
                fprintf(stderr, "mysql_init failed\n");
                exit(EXIT_FAILURE);
        }

        conn_ptr = mysql_real_connect(conn_ptr, "localhost", "chenqi", "helloworld",
                                      "test", 0, NULL, 0);

	if (conn_ptr)
	{
         	printf("Connection Success \n");
	}
        else
	{
         	printf("Connection failed \n");
	}

        mysql_close(conn_ptr);

	exit(EXIT_SUCCESS);
}

gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -o connect1

Example2: how to handle errors

#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"

int main(int argc, char *argv[])
{
        MYSQL conn;
        mysql_init(&conn);
        if (mysql_real_connect(&conn, "localhost", "chenqi",
	                       "i do not know", "test", 0, NULL, 0))
	{
                printf("Connection Success \n");
                mysql_close(&conn);
        }
        else
        {
                fprintf(stderr, "Connection Failed \n");
                if (mysql_errno(&conn))
                {
                        fprintf(stderr, "Connection error %d: %s \n",
                                mysql_errno(&conn), mysql_error(&conn));
                }
        }
        exit(EXIT_SUCCESS);
}

result:

chenqi@chenqi-laptop ~/MyPro/Database/access_with_c $ ./connect2
Connection Failed
Connection error 1045: Access denied for user ''chenqi''@''localhost'' (using password: YES)

Example3: how to insert and update

/* insert a row into the table children */
                ret = mysql_query(&conn, "insert into children(fname, age) values(''James'', 23)");
                if (!ret)
                {
                        printf("Inserted %lu rows \n",
                               (unsigned long)mysql_affected_rows(&conn));
                }
                else
                {
                        fprintf(stderr, "Insert error %d: %s \n",
                                mysql_errno(&conn), mysql_error(&conn));
                }
                /* update a row in the table children */
                ret = mysql_query(&conn, "update children set age = 24 where fname = ''James''");
                if (!ret)
                {
                        printf("Update %lu rows \n",
                               (unsigned long)mysql_affected_rows(&conn));
                }
                else
                {
                        fprintf(stderr, "Update error %d: %s \n",
                                mysql_errno(&conn), mysql_error(&conn));
                }

result:

chenqi@chenqi-laptop ~/MyPro/Database/access_with_c $ ./insert-update
Connection Success
Inserted 1 rows
Update 2 rows

Example4: how to retrieve data into C application

Step1: Issue the query (mysql_query)
Step2: Retrieve the data (mysql_store_result, mysql_use_result)
Step3: Process the data (mysql_fetch_row)
Step4: Tidy up if necessary (mysql_free_result)

For a large data set, mysql_use_result should be considered, because it uses less storage.

MySQL, like other SQL databases, gives back two sorts of data:
1. The retrieved information from the table, namely the column data
2. Data about the data, so-called metadata, such as column types and names

#include <stdlib.h>
#include <stdio.h>

#include "mysql.h"

MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;

void display_row()
{
	unsigned int field_count = 0;
	while(field_count < mysql_field_count(&my_connection))
	{
		if (sqlrow[field_count])
			printf("%12s", sqlrow[field_count]);
		else
			printf("%12s", "NULL");
		field_count++;
	}
	printf("\n");
}

/* show metadata of each column */
void display_header()
{
	MYSQL_FIELD *field_ptr;

	printf("Column Details:\n");
	while((field_ptr = mysql_fetch_field(res_ptr)) != NULL)
	{
		printf("\t Name: %s\n", field_ptr->name);
		printf("\t Type: ");
		if (IS_NUM(field_ptr->type))
		{
			printf("Numeric Field\n");
		}
		else
		{
			switch(field_ptr->type)
			{
			case FIELD_TYPE_VAR_STRING:
				printf("VARCHAR\n");
				break;
			case FIELD_TYPE_LONG:
				printf("LONG\n");
				break;
			default:
				printf("Type is %d, check in mysql_com.h\n", field_ptr->type);
			}
		} /* else */
		printf("\t Max_width %ld\n", field_ptr->max_length);
		if (field_ptr->flags & AUTO_INCREMENT_FLAG)
		{
			printf("\t Auto increments\n");
		}
		printf("\n");
	}	  /* while */
}

int main(int argc, char *argv[])
{
	int ret;
	mysql_init(&my_connection);
	if (mysql_real_connect(&my_connection, "localhost", "chenqi",
			       "helloworld", "test", 0, NULL, 0))
	{
		printf("Conncetion Success\n");
		ret = mysql_query(&my_connection, "select * from children");
		if (ret)	/* error */
		{
			printf("select error: %s\n", mysql_error(&my_connection));
		}
		else		/* ok */
		{
			res_ptr = mysql_store_result(&my_connection); /* mysql_use_result for an alternative */
			if (res_ptr)
			{
				printf("Retrieved %lu rows \n", (unsigned long)mysql_num_rows(res_ptr));
				display_header();
				while (sqlrow = mysql_fetch_row(res_ptr))
				{
///					printf("Fetching data ... \n");
					display_row();
				}
				if (mysql_errno(&my_connection))
				{
					fprintf(stderr, "Retrieve error: %s\n", mysql_error(&my_connection));
				}
				mysql_free_result(res_ptr); /* res_ptr != NULL */
			}
		}
		mysql_close(&my_connection);
	}
	else
	{
		fprintf(stderr, "Connection Failed\n");
		if (mysql_errno(&my_connection))
		{
			fprintf(stderr, "Connection error %d: %s\n",
				mysql_errno(&my_connection), mysql_error(&my_connection));
		}
		exit(EXIT_FAILURE);
	}
	exit(EXIT_SUCCESS);
}

Result:

chenqi@chenqi-laptop ~/MyPro/Database/access_with_c $ ./select1
Conncetion Success
Retrieved 12 rows
Column Details:
         Name: childno
         Type: Numeric Field
         Max_width 2
         Auto increments

         Name: fname
         Type: VARCHAR
         Max_width 8

         Name: age
         Type: Numeric Field
         Max_width 2

           1       Jenny          21
           2        Feby          25
           3    Chandler          12
           4      Monica          23
           5      Rachel          21
           6        Ross           2
           7         Joy          11
           8        Emma          11
           9       Gavin          14
          10      Andrew          21
          12       James          24
          13         Tom          13

.net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式

.net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式

便签记录Mysql,Sql server,Sqlite,Access四种数据库的简单连接方式

//using MySql.Data.MySqlClient; 
#region  执行简单SQL语句,使用MySQL查询
        static string  strConn = "server=.;database=Data20180608;uid=sa;pwd=123456;integrated Security=SSPI;persist Security info=false;";
        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int MyExecuteSql(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(strConn))
            {
                using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable MyQuery(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(strConn))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds.Tables[0];
            }
        }
        #endregion
Mysql

 

#region  执行简单SQL语句,使用SQL SERVER查询
        static string strConn = "Data Source=.;database=Data20180608;User id=root;Password=123456;pooling=false;CharSet=utf8;port=3306;";

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable Query(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds.Tables[0];
            }
        }
        #endregion
Sql server

 

//using System.Data.OleDb;
 public static string OtherPAth = "";
        public static string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
       public static string Sql = String.Empty;
        #region  执行简单SQL语句,使用OleDb查询

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(strConn + OtherPAth ))
            {
                using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

      


        /// <summary>
        /// 执行查询语句,返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable Query(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(strConn + OtherPAth))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
                return ds.Tables[0];
            }
        }

        /// <summary>
        /// 执行查询语句,返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable QueryDataName()
        {
            using (OleDbConnection connection = new OleDbConnection(strConn + OtherPAth))
            {
                DataTable ds = new DataTable();
                try
                {
                    connection.Open();
                    ds = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
                return ds;
            }
        }

        #endregion
Access

 

public static string strConn = @"Data Source=" + @"F:\资料文档\20190227\CAD\0625AnPin\CadDLLcl\Data\Cad_try0626.db";
        public static string Sql = String.Empty;

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(strConn))
            {
                //事务
                using (SQLiteTransaction singleTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                    {
                        try
                        {
                            connection.Open();
                            cmd.Transaction = singleTrans;
                            int rows = cmd.ExecuteNonQuery();
                            singleTrans.Commit();
                            return rows;
                        }
                        catch (System.Data.SqlClient.SqlException e)
                        {
                            connection.Close();
                            singleTrans.Rollback();
                            throw e;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回DataTable
        /// </summary>
        /// <param name = "SQLString" > 查询语句 </ param >
        /// < returns > DataSet </ returns >
        public static DataTable Query(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(strConn))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                    return ds.Tables[0];
                }
                catch (Exception ex)
                {
                    connection.Close();
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 执行存储过程,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteProc(string procName, SQLiteParameter[] coll)
        {
            using (SQLiteConnection connection = new SQLiteConnection(strConn))
            {
                //事务
                using (SQLiteTransaction singleTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(connection))
                    {
                        try
                        {
                            connection.Open();
                            for (int i = 0; i < coll.Length; i++)
                            {
                                cmd.Parameters.Add(coll[i]);
                            }
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandText = procName;
                            cmd.Transaction = singleTrans;
                            int rows = cmd.ExecuteNonQuery();
                            singleTrans.Commit();
                            return rows;
                        }
                        catch (System.Data.SqlClient.SqlException e)
                        {
                            connection.Close();
                            singleTrans.Rollback();
                            throw e;
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 执行带参数的SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlPar(string sqlPar, SQLiteParameter[] coll)
        {
            using (SQLiteConnection connection = new SQLiteConnection(strConn))
            {
                //事务
                using (SQLiteTransaction singleTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(connection))
                    {
                        try
                        {
                            connection.Open();
                            for (int i = 0; i < coll.Length; i++)
                            {
                                cmd.Parameters.Add(coll[i]);
                            }
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = sqlPar;
                            cmd.Transaction = singleTrans;
                            int rows = cmd.ExecuteNonQuery();
                            singleTrans.Commit();
                            return rows;
                        }
                        catch (System.Data.SqlClient.SqlException e)
                        {
                            connection.Close();
                            singleTrans.Rollback();
                            throw e;
                        }
                    }
                }
            }
        }
Sqlite

 

access mysql mssql 随机 10条数据的sql语句 原创

access mysql mssql 随机 10条数据的sql语句 原创

access 随机 10条数据的方法
复制代码 代码如下:

select * from table order by rnd(id)

其中rnd(id)中的id为表中的自增长字段
access随机显示记录(不重复)解决方案
复制代码 代码如下:

<%
''-------------------------数据库连接-----------------------
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" &_
"Data Source=" & Server.MapPath("data.mdb")
objConn.Open
''-------------------------数据库连接-----------------------

''-------------------------检索数据-----------------------
strSQL = "SELECT id,DataColumn FROM DataTable"
''Sql语句,检索数据库
Set objRS = Server.CreateObject("ADODB.Recordset")
''创建记录集
objRS.Open strSQL, objConn, 1, 1
''执行检索
Count=objRS.RecordCount
''得到记录总数
Item=4
''显示记录数
''-------------------------检索数据-----------------------
''-------------------------------------------------------------------------------
redim a(Item, 2),t(Count)
''定义2数组,数组a用来储存记录,数组t用来删选记录
''---------------------------------------
''初始数组数值,目的为了插入数据以后和此值做比较
for each j in t
j=0
next
''---------------------------------------
''---------------------------------------
'' 随机抽取记录号
Randomize timer ''初始化随机数生成器
for j=1 to Item
k=int(rnd*Count+1) ''从总数里面随机取一条记录
do while t(k)<>0 ''判断是否记录是否已经在数组中
k=int(rnd*Item+1)
loop
t(k)=1 ''第k条记录被选中
next
''--------------------------------------
j=1:i=1''定义下标
''--------------------------------------
'' 循环选取数据集objRS中的部分记录存放到数组中
Do While Not objRS.Eof
if t(j)=1 then
a(i,1)=objRS("id") ''记录id
a(i,2)=objRS("DataColumn") ''记录内容
i=i+1
end if
j=j+1
objRS.MoveNext
Loop
''--------------------------------------
''-------------------------------------------------------------------------------
''----------------------------显示内容--------------------
for i=1 to Item
Response.write "序号"&a(i,1)&"<br>"
Response.write "内容"&a(i,2)&"<p>"
next
''----------------------------显示内容--------------------
''---------------------------
''释放资源
objRs.Close
set objRs=nothing
objConn.Close
set objConn=nothing
''---------------------------
%>

mssql 随机 10条记录
复制代码 代码如下:

select * from talbe order by newid()


mysql 随机 10条记录
复制代码 代码如下:

select * from table order by rand() limit 0,10

原创请注明出处 www.jb51.net

Access 数据导入mysql_MySQL

Access 数据导入mysql_MySQL

bitsCN.com

从Access中提取若干信息,导入到mysql中。

 

 嗯,多简单的事呀。。。不过是SQL语句的导入导出嘛。。。我开始真的是这么想的。。。

 

 做的时候发现,Access没有导出SQL的功能,不想用第三方的东西。。。

 

 这里简单描述下我是怎么做的吧!

 

 1、在access中建个视图,得到自己想要的数据;

 

 2、把这个视图查询到的数据,导出成文本格式,我用的是CVS;

 

 3、用文本编辑器,把导出的数据 处理成 SQL语句(多亏了vim,用其他编辑器都不知道怎么办才好,打开都成问题,更不用说快速编辑了。。。UE打开后,滚轮都滚不动的说。。。);

 

 4、用mysql命令,导入mysql。

 

 思路很清晰,我就这么做了。直到最后一步,才发现问题:数据量太大(68万条),这一步很慢很慢。

 

 慢也就罢了,只做一次(等了我近2个小时),没什么关系。。。可是,马上发现,数据中时间格式不对。比如Access中是2011-1-1,而mysql这边,期望得到的是2011-01-01,就这一个时间,要改动几十万条记录,还不如重新导一份新的呢。。。

 

 于是,重复步骤2,得到数据。

 

 因为导入过程慢的实在太离谱了,就找了个mysqldump 备份出来的文件来看,看一看mysql官方觉得怎样导入数据会更快,于是发现了诸如下面的内容:

 


Sql代码 
LOCK TABLES `tablename` WRITE;  
ALTER TABLE `tablename` DISABLE KEYS;  
INSERT INTO `tablename` (id,name,password) VALUES   
-- 这里是数据  
;  
ALTER TABLE `tablename`ENABLE KEYS;  
UNLOCK TABLES; 

LOCK TABLES `tablename` WRITE;
ALTER TABLE `tablename` DISABLE KEYS;
INSERT INTO `tablename` (id,name,password) VALUES
-- 这里是数据
;
ALTER TABLE `tablename`ENABLE KEYS;
UNLOCK TABLES;
 

 很明显,这里的SQL从3个方面做了优化:

 

 1、加了只写的锁(解锁之前,不能查询,同时索引 可以最后做,插入数据 就会快啦);

 

 2、Disable了所有键(于是,就不用再做外键检查了,全心插入数据);

 

 3、insert into 用一条语句完成(一条语句 和 金条语句 的性能,差别不是一般的大啊,想想也觉得是。。。)。

 

 

 这样之后,几分钟就能搞定。

 

 

 另外,说一点文本处理的。。。

 

 一开始,习惯性的,要写成一条一条的SQL,于是想到了用宏来做。宏很简单,小数据量非常方便,不用大脑怎么思考。但是,做了一会,发现实在太慢了,大数据量,处理不了。

 

 我平时很少写vim脚本,现在想来,用脚本也会很慢,毕竟要一行行的执行呀。。。

 

 于是乎,写正则,查找替换。很快,几秒钟搞定一次替换。正则的威力,真不是一般的强大啊。。。上面说的时间格式的转换,也是在这里做的。

 

 注意:即使你的文本很好看,可以试试列编辑。一般行首适用,后面 几乎都不可用了。。。

 

 这里要说的是,不要把多行数据变成一行,没这个必要。变成一行后,可读性会变的很差,文本处理会变的非常的慢。如果一行匹配的次数过多,用g这个参数,往往会很慢。。。

 

 

 就说这些吧。。。

 

 重新理了下思路。。。

 

 下次估计10分钟就能搞定这样的事。。。

 

bitsCN.com

ACCESS数据库向MySQL快速迁移小程序(一)_MySQL

ACCESS数据库向MySQL快速迁移小程序(一)_MySQL

Access


  为开发的一个信息管理系统从以前试运行的开发机器上(Windows NT + IIS4.0 + Access)迁移至一台真正的Linux服务器上(Apache1.3.12 + PHP 4.03 + MySQL 3.23.26),其中数据库中的几十个表的内容迁移,开始让我小费了一些周折,从网上也下载了一些MySqL的客户软件或是数据库管理软件,写得较好的软件均有数据迁移功能,但其迁移方式不外乎两种,一种是采用文件引入方式,此种方式在处理数据库中有和分隔符相同的字符时,会产生错误,尤其是在处理ACCESS中的Memo字段,很容易出错,最后导致导出后的数据不是多了就是少了。而另一种支持ODBC直接导入的功能较强,基本可无错误地导入各个表的内容,但很遗憾,这必须是建立在ACCESS中表格的字段是英文是才可以,如在ACCESS中字段是中文名,一般也出错,不能成功导入。
  
  为此我只好花了点时间写了两个小程序,用于将ACCESS数据库的内容向MySQL迁移,经使用,效果还不错,特在此写出奉献给各位一试或评判。
  
  先概述一下使用方法,
  1,将ACCESS的数据库建立一个"system DSN";
    2,根据ACCESS数据库中各表的名称,在MySQL中建立相应的各个空表;
  3,运行fdlist.php;
    4,运行import.php;
    5,每运行一次3,4步可迁移一个表,然后修改fdlist.php中的ACCESS源表名和MySQL中的目标表名,再运行3,4步,直至迁移所有的表,
  
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  以下为 fdlist.php源程序
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   
  
  
  
  
   
  
    $dbconnection = @mysql_connect("yourmysqlserver", "mysqlaccount", "mysqlpassword") 
    
      or die ("can not connect to database server");
    
    @mysql_select_db("yourdatabase") 
         
         or die("

No Database,

") ; 
  
    $odbc_table = "youroriginaltable" ;  // The original table name in your ODBC database
  
    $mysql_table = "yournewtable" ;    // The new table name in your Mysql Database.
  
  ?>
  
  
  
  

  

Fields List of Two tables


  

  
  
  
    $conn = odbc_connect("task", "", "");
    
    $odbc_query = "select * from " . $odbc_table . " where 1=2";
    
    $recordsid = odbc_exec($conn, $odbc_query);
    
    $idcounts = odbc_num_fields( $recordsid ) ;
  
    $fdlist1 = "" ;
    
    for ( $i = 1 ; $i     
      $fdlist1 .=  odbc_field_name($recordsid,$i)."," ;
    
    echo "

Fd1 = " . $fdlist1 ;
    
    $fdlist1 = substr($fdlist1,0,strlen($fdlist1)-1) ;
    
    $fdlist2 = "" ;
  
    $sqlquery = "select * from " . $mysql_table . " where 1=2 " ; 
    
    $records2 = mysql_query ($sqlquery) ;
          
    $idcount2 = mysql_num_fields ( $records2 ) ;
       
    for ( $i = 0 ; $i     
      $fdlist2 .= mysql_field_name($records2,$i )."," ;
      
    echo "

FD2 = " . $fdlist2 ;
  
    $fdlist2 = substr($fdlist2,0,strlen($fdlist2)-1) ;
      
    $fp = fopen ("fdlist.txt","w") ;
    
    fwrite ($fp,$ctable) ;
    
    fwrite ($fp,"n");
    
    fwrite ($fp,$fdlist1) ;
    
    fwrite ($fp,"n");
    
    fwrite ($fp,$etable) ;
    
    fwrite ($fp,"n") ;
    
    fwrite ($fp,$fdlist2) ;
    
    fclose($fp) ;
      
    odbc_close($conn);
  
    if ( $idcount2 != $idcounts ) {
    
      echo "


". 
        
        "

The fields of two tables doesn''t match" ;
  
      echo "

ODBC_table Fields = " . $idcounts;
  
      echo "

MySQL_table Fields = " . $idcount2;
    }
  ?>
  
  

今天关于Access MySQL from C 用 C 访问 MySQL 数据库的分享就到这里,希望大家有所收获,若想了解更多关于.net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式、access mysql mssql 随机 10条数据的sql语句 原创、Access 数据导入mysql_MySQL、ACCESS数据库向MySQL快速迁移小程序(一)_MySQL等相关知识,可以在本站进行查询。

本文标签:

上一篇A Simple Introduction to Linux Daemon (with exa...

下一篇PHP iconv(): Unknown error (84)