當前位置:首頁 » 操作系統 » 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')。 五、測試 接下來寫一個測試用例來看一下使用批量插入的效果。

熱點內容
為什麼堆配置打不過蘋果 發布:2024-10-05 01:22:11 瀏覽:623
垃圾緩存的英文 發布:2024-10-05 01:13:34 瀏覽:947
md5加密c實現 發布:2024-10-05 01:13:31 瀏覽:299
updatesql兩個表 發布:2024-10-05 01:13:30 瀏覽:4
趙南起韓國訪問 發布:2024-10-05 01:04:00 瀏覽:985
基於pid演算法 發布:2024-10-05 00:41:22 瀏覽:925
有什麼手機配置低的還好玩 發布:2024-10-05 00:40:23 瀏覽:669
redis資料庫查詢 發布:2024-10-05 00:27:43 瀏覽:946
如何消除安卓的彈窗 發布:2024-10-05 00:26:59 瀏覽:427
wget下載文件夾 發布:2024-10-05 00:26:22 瀏覽:44