问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501
你好,欢迎来到懂视!登录注册
当前位置: 首页 - 正文

C#连接mysql数据库,执行查询报错

发布网友 发布时间:2022-05-02 16:10

我来回答

5个回答

懂视网 时间:2022-05-02 20:32

 

 1 /*
 2 C/C++连接MySQL数据库时,需要包含一个*.h的mysql头文件和一个mysql的lib文件
 3 1、初始化;
 4 2、连接数据库;
 5 3、执行sql查询语句;
 6 4、获取查询值;
 7 5、关闭
 8 */
 9 #include <stdio.h>
 10 #include <WinSock.h> 
 11 #include <mysql.h> 
 12 #include <Windows.h>
 13 #pragma comment(lib,"wsock32.lib")
 14 #pragma comment(lib,"libmysql.lib")
 15 
 16 MYSQL mysql;
 17 MYSQL_FIELD *fd; //字段列数组
 18 char field[32][32]; //存字段名二维数组
 19 MYSQL_RES *res; //行的一个查询结果集
 20 MYSQL_ROW column; //数据行的列
 21 char query[150]; //查询语句
 22 
 23 //函数声明
 24 bool ConnectDatabase(); 
 25 void FreeConnect();
 26 bool QueryDatabase(); 
 27 bool InsertData();
 28 bool ModifyData();
 29 bool DeleteData();
 30 
 31 int main(int argc, char **argv){
 32  ConnectDatabase();
 33  QueryDatabase();
 34  InsertData();
 35  QueryDatabase();
 36  ModifyData();
 37  QueryDatabase();
 38 //DeleteData();
 39 //QueryDatabase();
 40  FreeConnect();
 41 system("pause");
 42 return 0;
 43 }
 44 
 45 //连接数据库
 46 bool ConnectDatabase(){
 47 //Gets or initializes a MYSQL structure
 48 mysql_init(&mysql); 
 49 
 50 // Connects to a MySQL server
 51 const char host[] = "localhost";
 52 const char user[] = "root";
 53 const char passwd[] = "root";
 54 const char db[] = "employees";
 55 unsigned int port = 3306;
 56 const char *unix_socket = NULL;
 57 unsigned long client_flag = 0;
 58 
 59 //A MYSQL* connection handler if the connection was successful, 
 60 //NULL if the connection was unsuccessful. For a successful connection, 
 61 //the return value is the same as the value of the first parameter.
 62 if (mysql_real_connect(&mysql, host, user, passwd, db, port, unix_socket, client_flag)){
 63  printf("The connection was successful.
");
 64  return true;
 65  }
 66 else{
 67  //const char *mysql_error(MYSQL *mysql)
 68  //Returns the error message for the most recently invoked MySQL function
 69  //A null-terminated character string that describes the error. 
 70  //An empty string if no error occurred.
 71  printf("Error connecting to database:%s
", mysql_error(&mysql));
 72  return false;
 73  }
 74 }
 75 
 76 //释放资源
 77 //void mysql_free_result(MYSQL_RES *result)
 78 //Frees the memory allocated for a result set by mysql_store_result(), 
 79 //mysql_use_result(), mysql_list_dbs(), and so forth.
 80 //When you are done with a result set, you must free the memory it 
 81 //uses by calling mysql_free_result().
 82 //Do not attempt to access a result set after freeing it.
 83 
 84 //void mysql_close(MYSQL *mysql)
 85 //Closes a previously opened connection.mysql_close() also deallocates 
 86 //the connection handler pointed to by mysql if the handler was allocated automatically 
 87 //by mysql_init() or mysql_connect().
 88 void FreeConnect(){
 89  mysql_free_result(res);
 90 mysql_close(&mysql);
 91 }
 92 
 93 //查询数据
 94 bool QueryDatabase(){
 95 //将数据格式化输出到字符串
 96 sprintf_s(query, "select * from departments");
 97 //设置编码格式
 98 mysql_query(&mysql, "set names gbk"); 
 99 
100 //int mysql_query(MYSQL *mysql, const char *stmt_str)
101 //Executes an SQL query specified as a null-terminated string
102 //Executes the SQL statement pointed to by the null-terminated string stmt_str. 
103 //Normally, the string must consist of a single SQL statement without a terminating semicolon (;) or g. 
104 //If multiple-statement execution has been enabled, the string can contain several statements separated by semicolons.
105 //Return Values:Zero for success.Nonzero if an error occurred.
106 if (mysql_query(&mysql, query)){
107  printf("Query failed (%s)
", mysql_error(&mysql));
108  return false;
109  }
110 else{
111  printf("query success
");
112  }
113 
114 //MYSQL_RES *mysql_store_result(MYSQL *mysql)
115 //Retrieves a complete result set to the client
116 //mysql_store_result() reads the entire result of a query to the client, allocates a MYSQL_RES structure, and places the result into this structure.
117 //mysql_store_result() returns a null pointer if the statement did not return a result set(for example, if it was an INSERT statement).
118 //mysql_store_result() also returns a null pointer if reading of the result set failed.
119 //You can check whether an error occurred by checking whether mysql_error() returns a nonempty string.
120 //Return Values: A MYSQL_RES result structure with the results.NULL(0) if an error occurred.
121 res = mysql_store_result(&mysql);
122 if (!res){
123  printf("Couldn‘t get result from %s
", mysql_error(&mysql));
124  return false;
125  }
126 
127 //my_ulonglong mysql_affected_rows(MYSQL *mysql)
128 //It returns the number of rows changed, deleted, 
129 //or inserted by the last statement if it was an UPDATE, DELETE, or INSERT. 
130 //For SELECT statements, returns the number of rows in the result set.
131 printf("number of dataline returned: %d
", mysql_affected_rows(&mysql));
132 
133 //获取字段的信息
134 //MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)
135 //Returns the definition of one column of a result set as a MYSQL_FIELD structure.
136 //Call this function repeatedly to retrieve information about all columns in the result set.
137 
138 // 获取列数
139 int j = mysql_num_fields(res);
140 
141 char *str_field[32]; //存储字段信息
142 
143 //获取字段名
144 for (int i = 0; i < j; i++){ 
145  str_field[i] = mysql_fetch_field(res)->name;
146  }
147 
148 //打印字段
149 for (int i = 0; i < j; i++) 
150  printf("%10s	", str_field[i]);
151 printf("
");
152 
153 //打印查询结果
154 //MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
155 //Fetches the next row from the result set
156 while (column = mysql_fetch_row(res)){
157  printf("%10s	%10s
", column[0], column[1]);
158  }
159 return true;
160 }
161 
162 //插入数据
163 bool InsertData()
164 {
165 sprintf_s(query, "insert into departments values (‘dddd‘, ‘xxxxx‘);");
166 if (mysql_query(&mysql, query)) {
167  printf("Query failed (%s)
", mysql_error(&mysql));
168  return false;
169  }
170 else{
171  printf("Insert success
");
172  return true;
173  }
174 }
175 
176 //修改数据
177 bool ModifyData(){
178 sprintf_s(query, "update departments set dept_name=‘yyyyy‘ where dept_no=‘dddd‘");
179 if (mysql_query(&mysql, query)) {
180  printf("Query failed (%s)
", mysql_error(&mysql));
181  return false;
182  }
183 else{
184  printf("Insert success
");
185  return true;
186  }
187 }
188 
189 //删除数据
190 bool DeleteData()
191 {
192 sprintf_s(query, "delete from departments where dept_no=‘dddd‘;");
193 //char query[100];
194 //printf("please input the sql:
");
195 //gets_s(query); //手动输入sql语句
196 if (mysql_query(&mysql, query)) {
197  printf("Query failed (%s)
", mysql_error(&mysql));
198  return false;
199  }
200 else{
201  printf("Insert success
");
202  return true;
203  }
204 }

 

C/C++连接MySQL数据库执行查询(对employees进行查询)

标签:字符串   SQL_error   sep   center   get   exe   mat   locate   释放   

热心网友 时间:2022-05-02 17:40

数据库中的employer_name是不会存在空格的啊。记得,不管是添加数据,还是读取数据,都要trim();

热心网友 时间:2022-05-02 18:58

应该用转换字符串函数 trim('联英人才网 ')

热心网友 时间:2022-05-02 20:32

sql 中不会这样的,肯定是其他问题!
不过你数据最好trim一下!sql查询空格也计算在内的!

热心网友 时间:2022-05-02 22:24

用LIKE试试看呗
c#连接mysql出现“给定关键字不在字典中”错误解决方法

遇到“给定关键字不在字典中”错误时,首先需要确定编码方式是否正确。在连接MySQL数据库时,确保连接字符串中包含charset=utf8,如:data source=127.0.0.1;database=mydb; uid=root;pwd=root;charset=utf8;如果在查询表时出现问题,需检查表内字段的编码,确认是否一致。不一致时,使用工具如HeidiS...

c#连接 mysql 数据库 报错是什么原因

1、检查连接字符串是否有问题 2、mysql默认是不允许远程访问的,也就是如果通过IP、域名访问的话,默认是被关闭的,除非是localhost或者127.0.0.1可以访问,服务器如果不是这个IP,需要打开mysql 远程访问。具体如何打开,请【百度搜索:mysql 开启 远程访问】...

为什么C#查询MySql失败,ExecuteNonQuery语句报错?

出现这种问题有可能是两种情况 1.查询结果包含海量数据。长时间检索无响应。这种情况,需要优化SQL,尽量减少数据输出量。2.表结构损坏。可以通过 CHECK TABLE REPAIR TABLE 语句进行检测或修复。附 CHECK TABLE 语法说明 CHECK TABLE tbl_name[,tbl_name] ... [option] ...option= {QUICK | FAST |...

c# 连接MYSQL和MSSQL数据库的异常处理

SystemException这个类提供系统异常和应用程序之间的区别!AugumentException 这是当方法提供的任意一个参数无效时,引发次异常!ArithmeticException 此异常类是表示算术运算导致的错误!DataException 这是如果在实用ADO.NET组件时生成错误。FormatException 当参数格式不符合被调用方法的参数规范时引发的异常。IOE...

MySql 查询数据时间过长,导致程序报错 怎么解决

请检查你程序文件中,调用Mysql的模块,以C#为例,会使用ado.NET来操作Mysql数据库,在配置文件中,会有&lt;TimeOut&gt;属性,默认是60000ms 即一分钟.查询时,程序请求Sql =&gt;sql处理 =&gt;sql返回结果,如果处理过程超过60000ms 就会报错,将这个属性该为更大的数值即可解决,如果是其他语言开发的程序,应该也...

用C#连接操作MYSQL时,老是会超时,怎么处理SQL语句执超时啊,连接字符串...

在连接函数前加个 Max Pool Size = 512; 我的同样问题加了后就OK了 myconn = new SqlConnection("Max Pool Size = 512;Server= ; User ID= ;password= ; Initial Catalog= ");

c# (winform)连接Mysql数据库的登录程序

首先引用 MySql.Data.dll 给出一个例子。/// /// 运行查询 /// /// 单点查询语句 /// &lt;returns&gt;DbDataReader数据阅读器&lt;/returns&gt; /// &lt;exception cref="ConnectionException"&gt; /// 如果打开连接失败,或者运行的语句不正确则抛出连接异常 /// YuanHeng.Product.EHotel.BusiLayer.DAO.Conn...

C#链接MySQL数据库的实现步骤有哪些

C#连接数据库有以下几个步骤:1:使用配置的数据库连接串,创建数据库连接 Connection 对象2:构建操作的sql语句3:定义command对象4:打开数据连接5:执行命令举一个例子,删除操作 public class StudentService { //从配置文件中读取数据库连接字符串 private readonly static string connString ...

初学C#,用C#查询MySql数据库中的表,没有显示任何数据,求指导

MySqlDataReader 是一个返回的对象,他只是指向下一条信息,用while循环,读取,while(mdr.Read()){写上代码,Console.WriterLine(mdr["字段"]);}

C# 调用CMD 启动mysql数据库 过程中,窗口被阻塞,不往下执行了 求...

p.StandardInput.WriteLine("exit")之后调用这个方法试一下p.WaitForExit()调用这个方法试一下

声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:11247931@qq.com
阵亡和伤亡两个有什么区别? 阵亡和战死有什么区别? 某校五年级有256人其中女生有134人女生占五年级全体学生的几分之几男 ... 在迎国庆的日子里学校举行了一系列的活动五年级学生共有134人参加此次... 吃果冻什么意思 吃果冻什么含义 月什么溶溶 望月的歌词是什么? 形容海边日落的文案(描写海边夕阳余晖的优美句子) 《月下小景》沈从文 月下小景基本信息 qq邮箱全名 无线路由实现交换机功能 无线路由器,交换机是干什么用的,不要太专业,搞不懂 其实微信和手机QQ有啥区别?都能聊天都能语音…… 城市排水系统的体质有哪些 期货开户需要哪些条件 期货开户条件是什么,有什么限制吗? 设置收集初期雨水排入污水管网有时间要求吗 急求推流式曝气池的课程设计说明书参考 分流制排水的优缺点 排水系统对城市发展影响最大的是哪些方面 生活排水系统采用分流制的优缺点? 小天才手表怎么取消护眼模式? 小度x8距离保护,怎么不提醒? 轻巧夺冠《雪》《雷电颂》答案 为什么在手机APP上禁用了应用还能在小度在家上打开? 五年级下册语文同步 小度和手机哪个伤害大一点? 六年级下册语文同步18页 人教版初一语文上册练习册第7课 所有无线路由器都有交换机功能? 当单反相机用fn按钮选择闪光模式,闪光模式成灰色按不动,为什么 笔记本FN键失灵了,怎么通过别的途径把摄像头调出来? 富士相机上的Fn1和Fn2之间的关系 炒粉利怎么做如何做好吃 炒粉利片的做法,炒粉利片怎么做好吃,炒粉利片 粉利怎么煮才好吃 肉片炒粉利的做法,肉片炒粉利怎么做好吃,肉片 柳州有什么好吃的夜宵 柳州有什么好吃的,好玩的 如何用PS把图片做出双色印刷的效果 求PS自动分色动作! oppo手机pegmoo是什么意思 请问印刷厂出菲林的步骤? 在PS中分色一般会运用到什么工具? 我想学习计算机编程,请问需要什么样的课本,和怎么样的学习方法?? 哪里有免费[洪恩编程之道系列教程]C#程序入门下载啊? 国二c语言光盘如何安装 12864液晶不带字库的用C语言和51单片机编程 去哪打工?
  • 焦点

最新推荐

猜你喜欢

热门推荐