当前位置:首页 » 操作系统 » c数据库的插入

c数据库的插入

发布时间: 2022-04-29 11:32:49

㈠ 怎样用c语言给mysql数据库插数据

无论什么语言给什么数据库插入数据,用的都是
SQL语言
的insert
into语句。具体格式:
insert
into
表名(列名1,列名2,...,列名n)values('值1','值2',...,'值n');

㈡ C语言 如何将变量 插入mySQL数据库,mySQL C语言封装变量的问题

假如用户输入的姓名和年龄值分别保存在变量name,age中:
char sql_insert[200];
sprintf(sql_insert, "INSERT INTO table values('%s','%d');", name, age);
mysql_query(&mysql_conn, sql_insert);
上述语句在执行完sprintf语句后,sql_insert中保存的是INSERT查询语句字符串,sql_insert作为mysql_query()语句的参数即可实现正确的插入。

㈢ 如何用c语言向数据库中插入,查询数据

windows下操作数据库的方法有ODBC和ADO两种
源码不是一句两句的问题
相关的例子网上搜搜多的是

㈣ c#通过for循环多次向数据库中插入数据。

你的问题不甚清晰。需要插入的数据来源是在窗体中吗?SQL需要拼接吗?

给你一段代码参考,这段代码是将窗体中dataGridView中的数据循环插入数据库,循环过程中拼接SQL,并执行插入:

//主方法,拼接SQL并执行插入
privateintInsertInTo()
{
StringBuildersqlinsert=newStringBuilder();
StringBuildersqlvalue=newStringBuilder();
sqlinsert.Append("insertinto你的表名(");
sqlvalue.Append("values(");
intnum=0;//该变量用来获取插入多少条数据
for(inti=0;i<dataGridView1.Rows.Count;i++)
{
for(intc=0;c<dataGridView1.Columns.Count;c++)
{
sqlinsert.Append(dataGridView1.Columns[c].HeaderText+",");//赋值列名
sqlvalue.Append("'"+dataGridView1.Rows[i].Cells[c].Value.ToString()+"'");//赋值列对应的值
}
stringsql=sqlinsert.ToString().Substring(0,sqlinsert.Length-1)+")"+sqlvalue.ToString().Substring(0,sqlvalue.Length-1)+")";//拼接完整插入SQL
num+=Insert(sql);//调用插入方法,并接收返回的插入行数
}
returnnum;
}
//连接数据库并执行SQL
privateintInsert(stringsql)
{
stringconnstring="server=127.0.0.1\SQLEXPRESS;database=你的数据库名;uid=用户名;pwd=密码";
SqlConnectionconn=newSqlConnection(connstring);
SqlCommandcmd=newSqlCommand(sql,conn);
conn.Open();
intn=cmd.ExecuteNonQuery();//执行
conn.Close();
cmd.Dispose();
returnn;
}

赋值列名时可以放在循环外只赋值一次。

㈤ VS2008(C#)怎样向数据库中插入数据

namespace 请教
{
class Program
{
static void Main(string[] args)
{
Program pro=new Program();
bool iftrue=pro.InsertData();
if(iftrue)
{
Console.WriteLine("写什么你懂的!");
}
else
{
Consloe.Write("同上");
}
}
public bool InsertData()
{
string sqlCon="server="服务器名";database="数据库名";uid="";pwd=""";
string sql= "Insert into Users(Name,Password)Values('叶子','111')";
SqlConnection conn=new SqlConnection(sqlCon);
SqlCommand cmd=new SqlCommad();
cmd.CommandText =sql;
cmd.Connection=conn.Connection;
conn.open();
int val=cmd.ExecuteNonQuery();
if(val>=1)
{
return true;
}
else
{
return false;
}
}
}
}

㈥ C 语言数组插入 mysql 数据库 求助

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

int main(int argc, char *argv[])
{
MYSQL *my_con = malloc( sizeof(MYSQL) );
MYSQL_RES *my_res;
MYSQL_FIELD *my_field;
MYSQL_ROW my_row;
int rows, i;
int res;

int a[2] = {51,2};
printf("%3d ",a[0]);

mysql_init(my_con);
my_con = mysql_real_connect(my_con, "localhost", "root", "jwn.com",
"jwn", 0, NULL, CLIENT_FOUND_ROWS);
if( NULL == my_con )
error_quit("Connection fail", my_con);
printf("Connection success\n");

res = mysql_query(my_con,
"insert into class1(name, age, birthday) value('abc', 52, NOW());");

mysql_free_result(my_res);
mysql_close(my_con);
free(my_con);

return 0;
}

㈦ MySQL C API怎么实现数据库表的插入数据

MYSQL_OPT_READ_TIMEOUT 是 MySQL c api 客户端中用来设置读取超时时间的参数。在 MySQL 的官方文档中,该参数的描述是这样的:

  • MYSQL_OPT_READ_TIMEOUT (argument type: unsigned int *)The timeout in seconds for each attempt to read from the server. There are retries if necessary, so the total effective timeout value is three times the option value. You can set the value so that a lost connection can be detected earlier than the TCP/IPClose_Wait_Timeout value of 10 minutes.

  • 也就是说在需要的时候,实际的超时时间会是设定值的 3 倍。但是实际测试后发现实际的超时时间和设置的超时时间一致。

    而具体什么时候发生三倍超时,在文档中没有找到。所以对 MySQL 5.7.20 的源码进行了一些分析。

    使用 GDB 调试代码找了实际与 mysql server 通信的代码,如下:

    其中 vio_read() 函数中,使用 recv 和 poll 来读取报文和做读取超时。net_should_retry() 函数只有在发生 EINTR 时才会返回 true。从这段代码来看是符合测试结果的,并没有对读取进行三次重试。只有在读取操作被系统中断打断时才会重试,但是这个重试并没有次数限制。

    从上面代码的分析可以看出,代码的逻辑和文档的描述不符。于是在一顿搜索后,找到了一个 MySQL 的 BUG(Bug #31163)。该 BUG 报告了在MySQL5.0 中,MySQL c api 读取的实际超时时间是设置的三倍,与现有文档描述相符。于是对 MySQL 5.0.96 的代码又进行分析。

    同样使用 GDB 找到了通信部分的代码。这次找到了重试三次的代码,如下:

    这个版本的 MySQL api 的读写超时是直接使用的 setsockopt 设置的。第一次循环,在 A 点发生了第一次超时(虽然注释写的非阻塞,但是客户端的连接始终是阻塞模式的)。然后在 B 点将该 socket 设置为阻塞模式,C 点这里重置 retry 次数。由于设置了 alarm 第二次以后的循环会直接进入 D 点的这个分支,并且判断循环次数。作为客户端时net->retry_count 始终是 1,所以重试了两次,共计进行了 3 次 vioread 后从 E 点退出函数。

    由上面的分析可知,MySQL 文档对于该参数的描述已经过时,现在的 MYSQL_OPT_READ_TIMEOUT 并不会出现三倍超时的问题。而 Bug #31163 中的处理结果也是将文档中该参数的描述更新为实际读取超时时间是设定时间的三倍。也许是 MySQL 的维护者们在后续版本更新时忘记更新文档吧。

㈧ C语言如何将变量插入Mysql数据库

你数据库用的是什么引擎?事务有没有提交?
1、在执行语句的下一句设置断点或添加超时50s,查看执行过程中有没有报错,并且看insert语句执行后当时数据库里有没有记录。
2、超时时间过后流程走完,在看看数据库里是否有数据;

㈨ C#:几种数据库的大数据批量插入

首先说一下,IProvider里有一个用于实现批量插入的插件服务接口IBatcherProvider,此接口在前一篇文章中已经提到过了。 /// /// 提供数据批量处理的方法。 /// public interface IBatcherProvider : IProviderService { /// /// 将 的数据批量插入到数据库中。 /// /// 要批量插入的 。 /// 每批次写入的数据量。 void Insert(DataTable dataTable, int batchSize = 10000); } 一、SqlServer数据批量插入 SqlServer的批量插入很简单,使用SqlBulkCopy就可以,以下是该类的实现: /// /// 为 System.Data.SqlClient 提供的用于批量操作的方法。 /// public sealed class MsSqlBatcher : IBatcherProvider { /// /// 获取或设置提供者服务的上下文。 /// public ServiceContext ServiceContext { get; set; } /// /// 将 的数据批量插入到数据库中。 /// /// 要批量插入的 。 /// 每批次写入的数据量。 public void Insert(DataTable dataTable, int batchSize = 10000) { Checker.ArgumentNull(dataTable, "dataTable"); if (dataTable.Rows.Count == 0) { return; } using (var connection = (SqlConnection)ServiceContext.Database.CreateConnection()) { try { connection.TryOpen(); //给表名加上前后导符 var tableName = DbUtility.FormatByQuote(ServiceContext.Database.Provider.GetService(), dataTable.TableName); using (var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, null) { DestinationTableName = tableName, BatchSize = batchSize }) { //循环所有列,为bulk添加映射 dataTable.EachColumn(c => bulk.ColumnMappings.Add(c.ColumnName, c.ColumnName), c => !c.AutoIncrement); bulk.WriteToServer(dataTable); bulk.Close(); } } catch (Exception exp) { throw new BatcherException(exp); } finally { connection.TryClose(); } } } } SqlBulkCopy的ColumnMappings中列的名称受大小写敏感限制,因此在构造DataTable的时候应请注意列名要与表一致。 以上没有使用事务,使用事务在性能上会有一定的影响,如果要使用事务,可以设置SqlBulkCopyOptions.UseInternalTransaction。 二、Oracle数据批量插入 System.Data.OracleClient不支持批量插入,因此只能使用Oracle.DataAccess组件来作为提供者。 /// /// Oracle.Data.Access 组件提供的用于批量操作的方法。 /// public sealed class OracleAccessBatcher : IBatcherProvider { /// /// 获取或设置提供者服务的上下文。 /// public ServiceContext ServiceContext { get; set; } /// /// 将 的数据批量插入到数据库中。 /// /// 要批量插入的 。 /// 每批次写入的数据量。 public void Insert(DataTable dataTable, int batchSize = 10000) { Checker.ArgumentNull(dataTable, "dataTable"); if (dataTable.Rows.Count == 0) { return; } using (var connection = ServiceContext.Database.CreateConnection()) { try { connection.TryOpen(); using (var command = ServiceContext.Database.Provider.DbProviderFactory.CreateCommand()) { if (command == null) { throw new BatcherException(new ArgumentException("command")); } command.Connection = connection; command.CommandText = GenerateInserSql(ServiceContext.Database, command, dataTable); command.ExecuteNonQuery(); } } catch (Exception exp) { throw new BatcherException(exp); } finally { connection.TryClose(); } } } /// /// 生成插入数据的sql语句。 /// /// /// /// /// private string GenerateInserSql(IDatabase database, DbCommand command, DataTable table) { var names = new StringBuilder(); var values = new StringBuilder(); //将一个DataTable的数据转换为数组的数组 var data = table.ToArray(); //设置ArrayBindCount属性 command.GetType().GetProperty("ArrayBindCount").SetValue(command, table.Rows.Count, null); var syntax = database.Provider.GetService(); for (var i = 0; i < table.Columns.Count; i++) { var column = table.Columns[i]; var parameter = database.Provider.DbProviderFactory.CreateParameter(); if (parameter == null) { continue; } parameter.ParameterName = column.ColumnName; parameter.Direction = ParameterDirection.Input; parameter.DbType = column.DataType.GetDbType(); parameter.Value = data[i]; if (names.Length > 0) { names.Append(","); values.Append(","); } names.AppendFormat("{0}", DbUtility.FormatByQuote(syntax, column.ColumnName)); values.AppendFormat("{0}{1}", syntax.ParameterPrefix, column.ColumnName); command.Parameters.Add(parameter); } return string.Format("INSERT INTO {0}({1}) VALUES ({2})", DbUtility.FormatByQuote(syntax, table.TableName), names, values); } } 以上最重要的一步,就是将DataTable转为数组的数组表示,即object[][],前数组的上标是列的个数,后数组是行的个数,因此循环Columns将后数组作为Parameter的值,也就是说,参数的值是一个数组。而insert语句与一般的插入语句没有什么不一样。 三、SQLite数据批量插入 SQLite的批量插入只需开启事务就可以了,这个具体的原理不得而知。 public sealed class SQLiteBatcher : IBatcherProvider { /// /// 获取或设置提供者服务的上下文。 /// public ServiceContext ServiceContext { get; set; } /// /// 将 的数据批量插入到数据库中。 /// /// 要批量插入的 。 /// 每批次写入的数据量。 public void Insert(DataTable dataTable, int batchSize = 10000) { Checker.ArgumentNull(dataTable, "dataTable"); if (dataTable.Rows.Count == 0) { return; } using (var connection = ServiceContext.Database.CreateConnection()) { DbTransaction transcation = null; try { connection.TryOpen(); transcation = connection.BeginTransaction(); using (var command = ServiceContext.Database.Provider.DbProviderFactory.CreateCommand()) { if (command == null) { throw new BatcherException(new ArgumentException("command")); } command.Connection = connection; command.CommandText = GenerateInserSql(ServiceContext.Database, dataTable); if (command.CommandText == string.Empty) { return; } var flag = new AssertFlag(); dataTable.EachRow(row => { var first = flag.AssertTrue(); ProcessCommandParameters(dataTable, command, row, first); command.ExecuteNonQuery(); }); } transcation.Commit(); } catch (Exception exp) { if (transcation != null) { transcation.Rollback(); } throw new BatcherException(exp); } finally { connection.TryClose(); } } } private void ProcessCommandParameters(DataTable dataTable, DbCommand command, DataRow row, bool first) { for (var c = 0; c < dataTable.Columns.Count; c++) { DbParameter parameter; //首次创建参数,是为了使用缓存 if (first) { parameter = ServiceContext.Database.Provider.DbProviderFactory.CreateParameter(); parameter.ParameterName = dataTable.Columns[c].ColumnName; command.Parameters.Add(parameter); } else { parameter = command.Parameters[c]; } parameter.Value = row[c]; } } /// /// 生成插入数据的sql语句。 /// /// /// /// private string GenerateInserSql(IDatabase database, DataTable table) { var syntax = database.Provider.GetService(); var names = new StringBuilder(); var values = new StringBuilder(); var flag = new AssertFlag(); table.EachColumn(column => { if (!flag.AssertTrue()) { names.Append(","); values.Append(","); } names.Append(DbUtility.FormatByQuote(syntax, column.ColumnName)); values.AppendFormat("{0}{1}", syntax.ParameterPrefix, column.ColumnName); }); return string.Format("INSERT INTO {0}({1}) VALUES ({2})", DbUtility.FormatByQuote(syntax, table.TableName), names, values); } } 四、MySql数据批量插入 /// /// 为 MySql.Data 组件提供的用于批量操作的方法。 /// public sealed class MySqlBatcher : IBatcherProvider { /// /// 获取或设置提供者服务的上下文。 /// public ServiceContext ServiceContext { get; set; } /// /// 将 的数据批量插入到数据库中。 /// /// 要批量插入的 。 /// 每批次写入的数据量。 public void Insert(DataTable dataTable, int batchSize = 10000) { Checker.ArgumentNull(dataTable, "dataTable"); if (dataTable.Rows.Count == 0) { return; } using (var connection = ServiceContext.Database.CreateConnection()) { try { connection.TryOpen(); using (var command = ServiceContext.Database.Provider.DbProviderFactory.CreateCommand()) { if (command == null) { throw new BatcherException(new ArgumentException("command")); } command.Connection = connection; command.CommandText = GenerateInserSql(ServiceContext.Database, command, dataTable); if (command.CommandText == string.Empty) { return; } command.ExecuteNonQuery(); } } catch (Exception exp) { throw new BatcherException(exp); } finally { connection.TryClose(); } } } /// /// 生成插入数据的sql语句。 /// /// /// /// /// private string GenerateInserSql(IDatabase database, DbCommand command, DataTable table) { var names = new StringBuilder(); var values = new StringBuilder(); var types = new List(); var count = table.Columns.Count; var syntax = database.Provider.GetService(); table.EachColumn(c => { if (names.Length > 0) { names.Append(","); } names.AppendFormat("{0}", DbUtility.FormatByQuote(syntax, c.ColumnName)); types.Add(c.DataType.GetDbType()); }); var i = 0; foreach (DataRow row in table.Rows) { if (i > 0) { values.Append(","); } values.Append("("); for (var j = 0; j < count; j++) { if (j > 0) { values.Append(", "); } var isStrType = IsStringType(types[j]); var parameter = CreateParameter(database.Provider, isStrType, types[j], row[j], syntax.ParameterPrefix, i, j); if (parameter != null) { values.Append(parameter.ParameterName); command.Parameters.Add(parameter); } else if (isStrType) { values.AppendFormat("'{0}'", row[j]); } else { values.Append(row[j]); } } values.Append(")"); i++; } return string.Format("INSERT INTO {0}({1}) VALUES {2}", DbUtility.FormatByQuote(syntax, table.TableName), names, values); } /// /// 判断是否为字符串类别。 /// /// /// private bool IsStringType(DbType dbType) { return dbType == DbType.AnsiString || dbType == DbType.AnsiStringFixedLength || dbType == DbType.String || dbType == DbType.StringFixedLength; } /// /// 创建参数。 /// /// /// /// /// /// /// /// /// private DbParameter CreateParameter(IProvider provider, bool isStrType, DbType dbType, object value, char parPrefix, int row, int col) { //如果生成全部的参数,则速度会很慢,因此,只有数据类型为字符串(包含'号)和日期型时才添加参数 if ((isStrType && value.ToString().IndexOf('\'') != -1) || dbType == DbType.DateTime) { var name = string.Format("{0}p_{1}_{2}", parPrefix, row, col); var parameter = provider.DbProviderFactory.CreateParameter(); parameter.ParameterName = name; parameter.Direction = ParameterDirection.Input; parameter.DbType = dbType; parameter.Value = value; return parameter; } return null; } } MySql的批量插入,是将值全部写在语句的values里,例如,insert batcher(id, name) values(1, '1', 2, '2', 3, '3', ........ 10, '10')。 五、测试 接下来写一个测试用例来看一下使用批量插入的效果。

热点内容
google访问ip 发布:2024-10-04 23:19:28 浏览:51
陕西税票服务器地址 发布:2024-10-04 23:04:23 浏览:16
2014访问学者 发布:2024-10-04 22:59:37 浏览:917
c质数的算法 发布:2024-10-04 22:58:32 浏览:521
三星的浏览器在哪个文件夹 发布:2024-10-04 22:57:05 浏览:987
连接line的服务器地址 发布:2024-10-04 22:57:01 浏览:181
衣柜门尺寸简单算法 发布:2024-10-04 22:56:54 浏览:722
有什么软件可以清理缓存垃圾 发布:2024-10-04 22:55:24 浏览:755
手机电脑中配置是指的什么 发布:2024-10-04 22:53:53 浏览:156
扩容数据存储的优势 发布:2024-10-04 22:51:37 浏览:643