Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Inserter
- {
- private readonly MySqlConnection _connection;
- public Inserter()
- {
- MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder();
- sb.AllowBatch = true;
- sb.Database = "playground";
- sb.Server = "127.0.0.1";
- sb.UserID = "qwe";
- sb.Password = "qweqwe";
- sb.UseAffectedRows = false;
- sb.Pooling = true;
- _connection = new MySqlConnection(sb.ConnectionString);
- }
- private MySqlConnection Connection {
- get {
- if (_connection.State == ConnectionState.Closed || _connection.State == ConnectionState.Broken) _connection.Open();
- return _connection;
- }
- }
- string stub;
- private string GetRandomString(int len, int seed)
- {
- if (null != stub) return stub; //генерить рандомные строки дело затратное,
- //поэтому для тестирования вставок обойдемся одной. но ежели раскоменить здесь и (2),
- //то можно и "уникальные" сроки вставлять
- StringBuilder sb = new StringBuilder();
- byte[] ba = new byte[len];
- Random r = new Random(DateTime.Now.Ticks);
- for (int i = 0; i < len; i++)
- {
- r.NextBytes(ba);
- sb.Append((char)(65 + ba[i] % 25));
- }
- stub = sb.ToString(); // (2)
- return sb.ToString();
- }
- public TimeSpan PerformInsert(int count, int len, bool fake)
- {
- DateTime start = DateTime.Now;
- for (int i = 0; i < count; i++)
- {
- string s = GetRandomString(len, i);
- //Console.WriteLine(s);
- if (!fake) Insert(s);
- }
- return DateTime.Now.Subtract(start);
- }
- private void Insert(string s)
- {
- MySqlCommand c = new MySqlCommand();
- c.Connection = Connection;
- c.Transaction = Connection.BeginTransaction(); //комментим здесь и (3) чтобы отключить транзакции
- c.CommandText = "INSERT into `habr` set `col` = @col";
- c.Parameters.AddWithValue("@col", s);
- c.ExecuteNonQuery();
- c.Transaction.Commit(); // (3) с транзакциями помедленнее, примерно 3сек/1000
- c.Connection.Close();
- }
- public bool IsReady()
- {
- try
- {
- MySqlCommand c = new MySqlCommand();
- c.Connection = Connection;
- c.CommandText = "Select 1;";
- object o = c.ExecuteScalar();
- return 1 == Convert.ToInt32(o);
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- return false;
- }
- }
- /* USAGE example: */
- // Inserter i = new Inserter();
- // if (i.IsReady())
- // {
- // Console.WriteLine("ready");
- // TimeSpan ts= i.PerformInsert(1000, 2000, false);
- // Console.WriteLine(ts.ToString());
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement