停下来# 39;连续打开和关闭连接后,连接到本地主机上的MySql服务器
本文关键字:连接 主机 服务器 MySql 连续打 停下来 | 更新日期: 2023-09-27 17:50:34
我有一些mysql问题,我有一个名为'transactionNumber'和'counter'的列。
transactionNumber值可以是这样的:(不包括字母)
a. 12345, 1234566
b. 9876, 98332, 23423
c. 12347
d. -
'counter'列是一个字段,用于计算一行中有多少个transactionNumber。例如,上面的字母"a"有2个transactionNumber,字母"b"有3个等等,字母"d"计数为1。
但是计数器列在应用程序启动时为空。因此,我创建了一个方法,该方法将对每一行的transactionNUmber进行计数,并更新计数器列。
这是我的方法:private void TransactionNumberCounter(DataSet dsData)
{
for (int i = 0; i < dsData.Tables["data"].Rows.Count; i++)
{
DataRow dRow = dsData.Tables["data"].Rows[i];
string tNumber = dRow.ItemArray.GetValue(1).ToString();
string id = dRow.ItemArray.GetValue(0).ToString();
string[] numbers = tNumbers.Split(',');
char[] arr = new char[] { ''t', ''n' };
int tNumberCounter= 0;
List<string> listAccNumbers = new List<string>();
foreach (string number in numbers)
listAccNumbers.Add(number.TrimStart(arr));
tNumberCounter = listAccNumbers.Count;
string query = @"UPDATE bartran SET aNumberCounter = ? WHERE id = ?;";
OdbcParameter[] parameters = new OdbcParameter[]{
new OdbcParameter("?", aNumberCounter),
new OdbcParameter("?", id)
};
DBServer.ExecuteQuery(query, "database_name", parameters);
}
}
这个方法有效。但如果有数千行要计数,我会得到一个错误:
Can't connect to MySQL server on "localhost" (10061)"
所以我试着在这里为你们寻求帮助。如何计数t.Number和更新计数器字段的基础上的页面加载计数。提前感谢!
还有其他可行的方法吗?
EDIT:
下面是DBServer类:
using System;
using System.Data;
using System.Data.Odbc;
public static class DBServer
{
//Test
private const string Server = "localhost";
private const string Uid = "root";
private const string Pwd = "defaultpass";
//LIVE
//private const string Server = "ipaddress";
//private const string Uid = "root";
//private const string Pwd = "password";
public static DataTable GetTable(string query, string database)
{
using (OdbcConnection cn = new OdbcConnection(
string.Format("Driver={{MySQL ODBC 5.1 Driver}};Server={0};dataBase={1};User={2};Password={3};Option=3;",
Server, database, Uid, Pwd)))
{
using (OdbcCommand cmd = new OdbcCommand(query, cn))
{
DataTable dt = new DataTable();
cn.Open();
using (OdbcDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
public static DataTable GetTable(string query, string database, OdbcParameter[] parameters)
{
using (OdbcConnection cn = new OdbcConnection(
string.Format("Driver={{MySQL ODBC 5.1 Driver}};Server={0};database={1};User={2};Password={3};Option=3;",
Server, database, Uid, Pwd)))
{
using (OdbcCommand cmd = new OdbcCommand(query, cn))
{
if (parameters != null)
cmd.Parameters.AddRange(parameters);
DataTable dt = new DataTable();
cn.Open();
using (OdbcDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
/// <summary>
/// Executes query to the database (Parameterized)
/// </summary>
/// <param name="query">Query String</param>
/// <param name="database">Target Database</param>
/// <param name="parameters">Collection of parameters</param>
/// <returns>Number of affected records</returns>
public static int ExecuteQuery(string query, string database, OdbcParameter[] parameters)
{
using (OdbcConnection cn = new OdbcConnection( string.Format("Driver={{MySQL ODBC 5.1 Driver}};Server={0};database={1};User={2};Password={3};Option=3;",
Server, database, Uid, Pwd)))
{
using (OdbcCommand cmd = new OdbcCommand(query,cn))
{
if (parameters != null)
cmd.Parameters.AddRange(parameters);
cn.Open();
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// Check if the query has record (Parameterized)
/// </summary>
/// <param name="query">Query string</param>
/// <param name="database">Target database</param>
/// <param name="parameters">Collection of parameters</param>
/// <returns>true if has record else false</returns>
public static bool HasRecord(string query, string database, OdbcParameter[] parameters)
{
using (OdbcConnection cn = new OdbcConnection( string.Format("Driver={{MySQL ODBC 5.1 Driver}};Server={0};database={1};User={2};Password={3};Option=3;",
Server, database, Uid, Pwd)))
{
using (OdbcCommand cmd = new OdbcCommand(query,cn))
{
if (parameters != null)
cmd.Parameters.AddRange(parameters);
cn.Open();
using (OdbcDataReader reader = cmd.ExecuteReader())
{
return reader.HasRows;
}
}
}
}
/// <summary>
/// Check if the query has record
/// </summary>
/// <param name="query">Query string</param>
/// <param name="database">Target database</param>
/// <returns>true if has record else false</returns>
public static bool HasRecord(string query, string database)
{
using (OdbcConnection cn = new OdbcConnection(string.Format("Driver={{MySQL ODBC 5.1 Driver}};Server={0};database={1};User={2};Password={3};Option=3;",
Server, database, Uid, Pwd)))
{
using (OdbcCommand cmd = new OdbcCommand(query, cn))
{
cn.Open();
using (OdbcDataReader reader = cmd.ExecuteReader())
{
return reader.HasRows;
}
}
}
}
public static DataTable CallStoredProcedure(string query, string database, OdbcParameter[] parameters)
{
using (OdbcConnection cn = new OdbcConnection(
string.Format("Driver={{MySQL ODBC 5.1 Driver}};Server={0};database={1};User={2};Password={3};Option=3;",
Server, database, Uid, Pwd)))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand(query, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
cmd.Parameters.AddRange(parameters);
OdbcDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
}
}
}
不要实例化Command
对象,也不要在每次迭代中定义参数。你应该试着这样写代码:
string query = @"UPDATE bartran SET aNumberCounter = ? WHERE id = ?;";
string cnstr=@"Driver={{MySQL ODBC 5.1 Driver}};Server=localhost;dataBase=database_name;User=root;Password=;Option=3;";
using(OdbcConnection connection=new OdbcConnection(cnstr))
{
using(OdbcCommand cmd=new OdbcCommand(query,connection))
{
cmd.Parameters.Add("?",OdbcType.Int);
cmd.Parameters.Add("?",OdbcType.Int);
connection.Open();
for (int i = 0; i < dsData.Tables["data"].Rows.Count; i++)
{
...
cmd.Parameters[0].Value=aNumberCounter;
cmd.Parameters[1].Value=id;
cmd.ExecuteNonQuery();
}
connection.Close();
}
}
PS:你应该用MySql Provider API
而不是Odbc API
。
如果我是你,我会首先在循环内准备我的查询,并在循环后执行一次。这样,您将避免在数据库上进行多次往返。我有一个例子,在这里与相同的想法,但使用VB。. NET和其他数据库类,而不是ODBC。
Dim Command As New SqlCommand(_
"insert into hilmarc_cem_items " & _
"(CEMID, " & _
"ItemCode, " & _
"UnitPrice, " & _
"Quantity, " & _
"UOM) ", Connection)
Dim ItemCodes() As String = Request.Form.GetValues("ItemCode")
Dim UnitPrices() As String = Request.Form.GetValues("UnitPrice")
Dim Quantities() As String = Request.Form.GetValues("Quantity")
Dim UOMs() As String = Request.Form.GetValues("UOM")
'Prepare query, do not execute yet!'
For Counter = 0 To ItemCodes.Length - 1
Command.CommandText &= "select @CEMID, @ItemCode" & Counter & ", @UnitPrice" & Counter & ", @Quantity" & Counter & ", @UOM" & Counter & " "
Command.Parameters.Add("@ItemCode" & Counter, Data.SqlDbType.NVarChar).Value = ItemCodes(Counter)
Command.Parameters.Add("@Quantity" & Counter, Data.SqlDbType.Decimal).Value = Quantities(Counter)
Command.Parameters.Add("@UOM" & Counter, Data.SqlDbType.NVarChar).Value = UOMs(Counter)
Command.Parameters.Add("@UnitPrice" & Counter, Data.SqlDbType.Decimal).Value = UnitPrices(Counter)
If Not Counter = ItemCodes.Length - 1 Then
Command.CommandText &= "union all "
Else
Command.CommandText &= ";"
End If
Next
'After the preparation, execute the query'
Connection.Open()
Command.ExecuteNonQuery()
这个想法是有一个单一的查询,从数组中获取所有数据,并将它们添加到sqlCommand中作为参数。在循环之后,您将执行一次命令。查询看起来像这样:
insert into myTable
(CEMID,
ItemCode,
UnitPrice,
Quantity,
UOM)
select @CEMID, @ItemCode0, @UnitPrice0, @Quantity0, @UOM0
union all
select @CEMID, @ItemCode1, @UnitPrice1, @Quantity1, @UOM1
union all
select @CEMID, @ItemCode1, @UnitPrice1, @Quantity1, @UOM1
union all
以上代码,做批量插入,可以修改更新