private void button1_Click(object sender, EventArgs e) { try { MySqlConnection myConn = new MySqlConnection(); myConn.Host = "192.168.69.8"; myConn.Port = 3306; myConn.UserId = "cody"; myConn.Password = "******"; myConn.Open(); MySqlCommand myCommand = new MySqlCommand(" SELECT * FROM registration.regUser ;", myConn); MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(); myDataAdapter.SelectCommand = myCommand; DataTable dbDataSet = new DataTable(); myDataAdapter.Fill(dbDataSet); BindingSource bSource = new BindingSource(); bSource.DataSource = dbDataSet; dataGridView1.DataSource = bSource; myDataAdapter.Update(dbDataSet); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public int fjöldi_rada() { MySqlConnection connection; string connectionString = "Server=10.0.105.33;Database=Leikur;Uid=first;Pwd=first;"; connection = new MySqlConnection(connectionString); connection.Open(); string query = @"SELECT * FROM spilari"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); MySqlDataReader queryCommandReader = cmd.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(queryCommandReader); MySqlDataAdapter adapter = new MySqlDataAdapter(); DataSet ds = new DataSet(); adapter.SelectCommand = cmd; adapter.Fill(ds, "SQL Temp Table"); adapter.Dispose(); cmd.Dispose(); return ds.Tables[0].Rows.Count; }
public void SettingAgeOnCommand() { execSQL("CREATE TABLE test2 (id INT, name VARCHAR(20), name2 VARCHAR(20))"); execSQL("INSERT INTO test2 VALUES (1, 'boo', 'hoo'), (2, 'first', 'last'), (3, 'fred', 'flintstone')"); GenericListener listener = new GenericListener(); string connStr = GetConnectionString(true) + ";logging=true;table cache=true;default table cache age=1"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("test2", c); cmd.CommandType = CommandType.TableDirect; cmd.CacheAge = 20; ConsumeReader(cmd); Thread.Sleep(1000); // now run the query again but this time it shouldn't generate a call to the database // since we have overriden the connection string cache age of 1 second and set it // to 20 seconds on our command ConsumeReader(cmd); } Assert.AreEqual(1, listener.Find("Resultset Opened: field(s) = 3")); }
public void CancelSelect() { if (version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))"); for (int i=0; i < 10000; i++) execSQL("INSERT INTO Test VALUES (NULL, 'my string')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); cmd.CommandTimeout = 0; int rows = 0; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); cmd.Cancel(); try { while (reader.Read()) { rows++; } } catch (Exception ex) { Assert.Fail(ex.Message); } } Assert.IsTrue(rows < 10000); }
public void CancelSingleQuery() { if (st.Version < new Version(5, 0)) return; // first we need a routine that will run for a bit st.execSQL(@"CREATE PROCEDURE spTest(duration INT) BEGIN SELECT SLEEP(duration); END"); MySqlCommand cmd = new MySqlCommand("spTest", st.conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("duration", 10); // now we start execution of the command CommandInvokerDelegate d = new CommandInvokerDelegate(CommandRunner); d.BeginInvoke(cmd, null, null); // sleep 1 seconds Thread.Sleep(1000); // now cancel the command cmd.Cancel(); resetEvent.WaitOne(); }
public void AddingParametersUsingInsert() { MySqlCommand cmd = new MySqlCommand(); cmd.Parameters.Insert(0, new MySqlParameter("?id", MySqlDbType.Int32)); MySqlParameter p = cmd.Parameters["?id"]; Assert.AreEqual("?id", p.ParameterName); }
public static void updatePagamenti_gruppo(Pagamenti_gruppo item) { using (MySqlConnection cnMySql = new MySqlConnection(connectionString)) { cnMySql.Open(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("UPDATE antique.pagamenti_gruppo "); sb.Append("SET "); sb.Append("`id_pagamenti` = ?id_pagamenti, "); sb.Append("`transaction_id` = ?transaction_id, "); sb.Append("`tipo_pagamento` = ?tipo_pagamento, "); sb.Append("`nome_esecutore` = ?nome_esecutore, "); sb.Append("`email_esecutore` = ?email_esecutore, "); sb.Append("`data_pagamento` = ?data_pagamento, "); sb.Append("`importo_pagamento` = ?importo_pagamento, "); sb.Append("WHERE id=?id;"); using (MySqlCommand cmd = new MySqlCommand(sb.ToString(), cnMySql)) { //lista parametri comando try { cmd.ExecuteNonQuery(); } catch (MySqlException ex) { EventLogger.LogError("Errore durante l'aggiornamento dell'oggetto Pagamenti_gruppo nel database.", ex); } } cnMySql.Close(); } }
public static void insertPagamenti_gruppo(Pagamenti_gruppo item) { using (MySqlConnection cnMySql = new MySqlConnection(connectionString)) { cnMySql.Open(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("INSERT INTO antique.pagamenti_gruppo(`id_pagamenti`, `transaction_id`, `tipo_pagamento`, `nome_esecutore`, `email_esecutore`, `data_pagamento`, `importo_pagamento`)"); sb.Append("VALUES "); sb.Append("(?id_pagamenti, ?transaction_id, ?tipo_pagamento, ?nome_esecutore, ?email_esecutore, ?data_pagamento, ?importo_pagamento)"); using (MySqlCommand cmd = new MySqlCommand(sb.ToString(), cnMySql)) { try { cmd.ExecuteNonQuery(); } catch (MySqlException ex) { EventLogger.LogError("Errore durante l'inserimento dell'oggetto Pagamenti_gruppo nel database.", ex); } } cnMySql.Close(); } }
public void AggregateTypesTest() { execSQL("CREATE TABLE foo (abigint bigint, aint int)"); execSQL("INSERT INTO foo VALUES (1, 2)"); execSQL("INSERT INTO foo VALUES (2, 3)"); execSQL("INSERT INTO foo VALUES (3, 4)"); execSQL("INSERT INTO foo VALUES (3, 5)"); // Try a normal query string NORMAL_QRY = "SELECT abigint, aint FROM foo WHERE abigint = {0}"; string qry = String.Format(NORMAL_QRY, 3); MySqlCommand cmd = new MySqlCommand(qry, conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { reader.GetInt64(0); reader.GetInt32(1); // <--- aint... this succeeds } } cmd.CommandText = "SELECT abigint, max(aint) FROM foo GROUP BY abigint"; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { reader.GetInt64(0); reader.GetInt64(1); // <--- max(aint)... this fails } } }
public void BadIndexUsed() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id INT, name VARCHAR(20) PRIMARY KEY)"); execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT name FROM Test WHERE id=3", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); } Assert.AreEqual(6, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT name FROM Test WHERE id=3")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 1, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: The following columns were not accessed: name")); Assert.IsTrue(listener.Strings[4].Contains("Resultset Closed. Total rows=1, skipped rows=0, size (bytes)=6")); Assert.IsTrue(listener.Strings[5].Contains("Query Closed")); }
public void Warnings() { if (version < new Version(4, 1)) return; conn.InfoMessage += new MySqlInfoMessageEventHandler(WarningsInfoMessage); execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test (name VARCHAR(10))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES ('12345678901')", conn); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (reader != null) reader.Close(); } }
void TransactionScopeInternal(bool commit) { MySqlConnection c = new MySqlConnection(GetConnectionString(true)); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ('a', 'name', 'name2')", c); try { using (TransactionScope ts = new TransactionScope()) { c.Open(); cmd.ExecuteNonQuery(); if (commit) ts.Complete(); } cmd.CommandText = "SELECT COUNT(*) FROM Test"; object count = cmd.ExecuteScalar(); Assert.AreEqual(commit ? 1 : 0, count); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (c != null) { c.Close(); } } }
public void CommitAfterConnectionDead() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id INT, name VARCHAR(20))"); string connStr = GetConnectionString(true) + ";pooling=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlTransaction trans = c.BeginTransaction(); using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, 'boo')", c)) { cmd.ExecuteNonQuery(); } KillConnection(c); try { trans.Commit(); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { } Assert.AreEqual(ConnectionState.Closed, c.State); c.Close(); // this should work even though we are closed } }
public void Simple() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, dec1 DECIMAL(5,2), name VARCHAR(100))"); execSQL("INSERT INTO Test VALUES (1, 345.12, 'abcd')"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1,345.12,'abcd')", conn); cmd.Prepare(); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; cmd.Prepare(); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual(345.12, reader.GetDecimal(1)); Assert.AreEqual("abcd", reader.GetString(2)); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (reader != null) reader.Close(); } }
public void Bug51610() { MySqlCommand cmd = new MySqlCommand("SELECT 'ABC', (0/`QOH`) from (SELECT 1 as `QOH`) `d1`", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ABC", reader.GetString(0)); Assert.AreEqual(0, reader.GetInt32(1)); } cmd.CommandText = "SELECT 'ABC', (0-`QOH`) from (SELECT 1 as `QOH`) `d1`"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ABC", reader.GetString(0)); Assert.AreEqual(-1, reader.GetInt32(1)); } cmd.CommandText = "SELECT 'test 2010-03-04 @ 10:14'"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("test 2010-03-04 @ 10:14", reader.GetString(0)); } }
public void TestReader() { execSQL("INSERT INTO Test VALUES('P', 'Test1', 'Test2')"); MySqlTransaction txn = conn.BeginTransaction(); MySqlConnection c = txn.Connection; Assert.AreEqual( conn, c ); MySqlCommand cmd = new MySqlCommand("SELECT name, name2 FROM Test WHERE key2='P'", conn, txn); MySqlTransaction t2 = cmd.Transaction; Assert.AreEqual( txn, t2 ); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Close(); txn.Commit(); } catch (Exception ex) { Assert.Fail( ex.Message ); txn.Rollback(); } finally { if (reader != null) reader.Close(); } }
public void Timeout() { for (int i=1; i < 10; i++) execSQL("INSERT INTO Test VALUES (" + i + ", 'This is a long text string that I am inserting')"); // we create a new connection so our base one is not closed MySqlConnection c2 = new MySqlConnection(conn.ConnectionString); c2.Open(); KillConnection(c2); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c2); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Read(); reader.Read(); reader.Close(); Assert.Fail("We should not reach this code"); } catch (Exception) { Assert.AreEqual(ConnectionState.Closed, c2.State); } finally { if (reader != null) reader.Close(); c2.Close(); } }
public void VarBinary() { if (Version < new Version(4, 1)) return; execSQL("DROP TABLE IF EXISTS test"); createTable("CREATE TABLE test (id int, name varchar(200) collate utf8_bin) charset utf8", "InnoDB"); execSQL("INSERT INTO test VALUES (1, 'Test1')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", conn); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); Assert.IsTrue(reader.Read()); object o = reader.GetValue(1); Assert.IsTrue(o is string); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (reader != null) reader.Close(); } }
public void FieldConversion() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); short s = reader.GetInt16(0); long l = reader.GetInt64(0); string str = reader.GetString(1); } Assert.AreEqual(6, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT * FROM Test")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: The field 'id' was converted to the following types: Int16,Int64")); Assert.IsTrue(listener.Strings[4].Contains("Resultset Closed. Total rows=1, skipped rows=0, size (bytes)=8")); Assert.IsTrue(listener.Strings[5].Contains("Query Closed")); }
public void Unicode() { if (version < new Version(4, 1)) return; execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (u2 varchar(255) CHARACTER SET ucs2)"); MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8"); c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ( CONVERT('困巫忘否役' using ucs2))", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Read(); string s1 = reader.GetString(0); Assert.AreEqual("困巫忘否役", s1); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (reader != null) reader.Close(); c.Close(); } }
public void ExecuteNonQuery() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test (id int)"); execSQL("CREATE PROCEDURE spTest() BEGIN SET @x=0; REPEAT INSERT INTO test VALUES(@x); " + "SET @x=@x+1; UNTIL @x = 300 END REPEAT; END"); MySqlCommand proc = new MySqlCommand("spTest", conn); proc.CommandType = CommandType.StoredProcedure; IAsyncResult iar = proc.BeginExecuteNonQuery(); int count = 0; while (!iar.IsCompleted) { count++; System.Threading.Thread.Sleep(20); } proc.EndExecuteNonQuery(iar); Assert.IsTrue(count > 0); proc.CommandType = CommandType.Text; proc.CommandText = "SELECT COUNT(*) FROM test"; object cnt = proc.ExecuteScalar(); Assert.AreEqual(300, cnt); }
public void BinaryAndVarBinaryParameters() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(OUT out1 BINARY(20), OUT out2 VARBINARY(20)) " + "BEGIN SET out1 = 'out1'; SET out2='out2'; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("out1", MySqlDbType.Binary); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.Parameters.Add("out2", MySqlDbType.VarBinary); cmd.Parameters[1].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); byte[] out1 = (byte[])cmd.Parameters[0].Value; Assert.AreEqual('o', out1[0]); Assert.AreEqual('u', out1[1]); Assert.AreEqual('t', out1[2]); Assert.AreEqual('1', out1[3]); out1 = (byte[])cmd.Parameters[1].Value; Assert.AreEqual('o', out1[0]); Assert.AreEqual('u', out1[1]); Assert.AreEqual('t', out1[2]); Assert.AreEqual('2', out1[3]); }
public void EscapedBackslash() { execSQL("CREATE TABLE Test(id INT, name VARCHAR(20))"); MySqlCommand cmd = new MySqlCommand(@"INSERT INTO Test VALUES (1, '\\=\\')", conn); cmd.ExecuteNonQuery(); }
public void LastInsertid() { execSQL("DROP TABLE Test"); execSQL("CREATE TABLE Test(id int auto_increment, name varchar(20), primary key(id))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(NULL, 'test')", conn); cmd.ExecuteNonQuery(); Assert.AreEqual(1, cmd.LastInsertedId); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Read(); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (reader != null) reader.Close(); } Assert.AreEqual(2, cmd.LastInsertedId); cmd.CommandText = "SELECT id FROM Test"; cmd.ExecuteScalar(); Assert.AreEqual(-1, cmd.LastInsertedId); }
public void Blobs() { execSQL("CREATE TABLE Test (id INT, blob1 LONGBLOB, text1 LONGTEXT)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?blob1, ?text1)", conn); byte[] bytes = Utils.CreateBlob(400000); string inStr = "This is my text"; cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?blob1", bytes); cmd.Parameters.AddWithValue("?text1", inStr); cmd.Prepare(); int count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count); cmd.CommandText = "SELECT * FROM Test"; cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual(bytes.Length, reader.GetBytes(1, 0, null, 0, 0)); byte[] outBytes = new byte[bytes.Length]; reader.GetBytes(1, 0, outBytes, 0, bytes.Length); for (int x = 0; x < bytes.Length; x++) Assert.AreEqual(bytes[x], outBytes[x]); Assert.AreEqual(inStr, reader.GetString(2)); } }
public MySqlReader(MySqlCommand command) { if (command.Type == MySqlCommandType.SELECT) { TryFill(command); } }
public void ProblemCharsInSQLUTF8() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), mt MEDIUMTEXT, " + "PRIMARY KEY(id)) CHAR SET utf8"); using (MySqlConnection c = new MySqlConnection(GetConnectionString(true) + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?text, ?mt)", c); cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?text", "This is my;test ? string–’‘’“”…"); cmd.Parameters.AddWithValue("?mt", "My MT string: ?"); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("This is my;test ? string–’‘’“”…", reader.GetString(1)); Assert.AreEqual("My MT string: ?", reader.GetString(2)); } } }
public void PossibleValues() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest (id INT UNSIGNED ZEROFILL, dec1 DECIMAL(10,2), name VARCHAR(20) /* this is a comment */ CHARACTER SET ascii, t1 TINYTEXT BINARY, t2 ENUM('a','b','c'), t3 /* comment */ SET(/* comment */'1','2','3')) BEGIN SELECT name; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; //MySqlCommandBuilder.DeriveParameters(cmd); Assert.IsNull(cmd.Parameters["@id"].PossibleValues); Assert.IsNull(cmd.Parameters["@dec1"].PossibleValues); Assert.IsNull(cmd.Parameters["@name"].PossibleValues); Assert.IsNull(cmd.Parameters["@t1"].PossibleValues); MySqlParameter t2 = cmd.Parameters["@t2"]; Assert.IsNotNull(t2.PossibleValues); Assert.AreEqual("a", t2.PossibleValues[0]); Assert.AreEqual("b", t2.PossibleValues[1]); Assert.AreEqual("c", t2.PossibleValues[2]); MySqlParameter t3 = cmd.Parameters["@t3"]; Assert.IsNotNull(t3.PossibleValues); Assert.AreEqual("1", t3.PossibleValues[0]); Assert.AreEqual("2", t3.PossibleValues[1]); Assert.AreEqual("3", t3.PossibleValues[2]); }
public void ArabicCalendars() { execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test(dt DATETIME)"); execSQL("INSERT INTO test VALUES ('2007-01-01 12:30:45')"); CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo c = new CultureInfo("ar-SA"); Thread.CurrentThread.CurrentCulture = c; Thread.CurrentThread.CurrentUICulture = c; try { MySqlCommand cmd = new MySqlCommand("SELECT dt FROM test", conn); DateTime dt = (DateTime)cmd.ExecuteScalar(); Assert.AreEqual(2007, dt.Year); Assert.AreEqual(1, dt.Month); Assert.AreEqual(1, dt.Day); Assert.AreEqual(12, dt.Hour); Assert.AreEqual(30, dt.Minute); Assert.AreEqual(45, dt.Second); } catch (Exception ex) { Assert.Fail(ex.Message); } Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; }
public void ExecuteReader() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test (id int)"); execSQL("CREATE PROCEDURE spTest() BEGIN INSERT INTO test VALUES(1); " + "SELECT SLEEP(2); SELECT 'done'; END"); MySqlCommand proc = new MySqlCommand("spTest", conn); proc.CommandType = CommandType.StoredProcedure; IAsyncResult iar = proc.BeginExecuteReader(); int count = 0; while (!iar.IsCompleted) { count++; System.Threading.Thread.Sleep(20); } using (MySqlDataReader reader = proc.EndExecuteReader(iar)) { Assert.IsNotNull(reader); Assert.IsTrue(count > 0, "count > 0"); Assert.IsTrue(reader.Read(), "can read"); Assert.IsTrue(reader.NextResult()); Assert.IsTrue(reader.Read()); Assert.AreEqual("done", reader.GetString(0)); reader.Close(); proc.CommandType = CommandType.Text; proc.CommandText = "SELECT COUNT(*) FROM test"; object cnt = proc.ExecuteScalar(); Assert.AreEqual(1, cnt); } }
private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (MySqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } }
public List <object> RetrieveObjects(Type t, MySqlCommand command) { List <object> items = new List <object>(); DataTable table = RetrieveDataTable(command); Dictionary <string, ColumnProperty> typeProps = ColumnProperty.GetCollumns(MySQLHelper.Instance, t); DataColumnCollection columns = table.Columns; for (int r = 0; r < table.Rows.Count; r++) { object item = Activator.CreateInstance(t); try { foreach (DataColumn col in columns) { if (col.DataType == typeof(DBNull)) { continue; } if (typeProps.ContainsKey(col.ColumnName)) { typeProps[col.ColumnName].SetValue(item, table.Rows[r][col]); } } items.Add(item); } catch// (Exception ex) { //Skip Property } } return(items); }
public bool editRoom(int id, string type, string status) { MySqlCommand command = new MySqlCommand(); string insertQuery = "UPDATE rooms SET type=@type,status=@status WHERE id=@id "; command.CommandText = insertQuery; command.Connection = conn.getConnection(); command.Parameters.Add("@id", MySqlDbType.Int32).Value = id; command.Parameters.Add("@type", MySqlDbType.VarChar).Value = type; command.Parameters.Add("@status", MySqlDbType.VarChar).Value = status; conn.openConnection(); if (command.ExecuteNonQuery() == 1) { conn.closeConnection(); return(true); } else { conn.closeConnection(); return(false); } }
//没用到过 public static MySqlDataReader DataReader_ExecuteReader(string connectionStringStr, string sqlStr) { MySqlConnection cnn = null; MySqlCommand cmd = null; MySqlDataReader rst = null; try { cnn = new MySqlConnection(connectionStringStr); cnn.Open(); cmd = new MySqlCommand(); cmd.Connection = cnn; cmd.CommandText = sqlStr; cmd.CommandTimeout = 1000; rst = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); } catch (Exception e) { System.Console.WriteLine("ex!\n"); } return(rst); }
private void btn_guardar_Click(object sender, EventArgs e) { if (conexion.State == System.Data.ConnectionState.Closed) { conexion.Open(); } MySqlCommand Modificaemp = new MySqlCommand("update inventario set Nombre_producto=@Nombre_producto,Tipo=@Tipo,Status=@Status,Costo=@Costo where id_inven=@id_inven", conexion); Modificaemp.Parameters.AddWithValue("@Nombre_producto", text_nombre_producto.Text); Modificaemp.Parameters.AddWithValue("@Tipo", text_tipo.Text); Modificaemp.Parameters.AddWithValue("@Status", text_status.Text); Modificaemp.Parameters.AddWithValue("@Costo", text_costo.Text); int N = int.Parse(comboBox1.Text); Modificaemp.Parameters.AddWithValue("@id_inven", N); Modificaemp.ExecuteNonQuery(); conexion.Close(); text_nombre_producto.Clear(); text_tipo.Clear(); text_status.Clear(); text_costo.Clear(); MessageBox.Show("Modificación existosa!"); }
public bool addcount(int randomNumber, String username) { MySqlCommand command = new MySqlCommand(); String count = "INSERT INTO `count`(`id`,`username`) VALUES (@id,@username)"; command.CommandText = count; command.Connection = conn.getConnection(); command.Parameters.Add("@id", MySqlDbType.Int32).Value = randomNumber; command.Parameters.Add("@username", MySqlDbType.VarChar).Value = username; conn.openConnection(); if (command.ExecuteNonQuery() == 1) { conn.closeConnection(); return(true); } else { conn.closeConnection(); return(false); } }
public void excluirPedido(int pedidoID) { con = new MySqlConnection(); connection = new Connection.Connection(); con.ConnectionString = connection.getConnectionString(); string query = "CALL excluir_pedido(?PedidoID);"; try { con.Open(); MySqlCommand command = new MySqlCommand(query, con); command.Parameters.AddWithValue("?PedidoID", pedidoID); command.ExecuteNonQuery(); } finally { con.Close(); MessageBox.Show("Pedido removido com sucesso.", "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public static List<Client> GetAll() { List<Client> allClients = new List<Client> {}; MySqlConnection conn = DB.Connection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"SELECT * FROM clients;"; MySqlDataReader rdr = cmd.ExecuteReader() as MySqlDataReader; while(rdr.Read()) { int clientId = rdr.GetInt32(0); string clientName = rdr.GetString(1); string clientEmail = rdr.GetString(2); Client newClient = new Client(clientName, clientEmail, clientId); allClients.Add(newClient); } conn.Close(); if (conn != null) { conn.Dispose(); } return allClients; }
public override List <Subdomain> GetSubdomains(string domainName) { var _tmp = new List <Subdomain>(); using (MySqlConnection _conn = new MySqlConnection(connectionString)) { _conn.Open(); using (MySqlCommand _cmd = new MySqlCommand(@"SELECT subdomains.name, domains.name AS domain, sys_users.login, accounts.password, subdomains.sys_user_type FROM accounts RIGHT OUTER JOIN sys_users ON accounts.id = sys_users.account_id RIGHT OUTER JOIN subdomains ON sys_users.id = subdomains.sys_user_id LEFT OUTER JOIN domains ON subdomains.dom_id = domains.id WHERE domains.name = @NAME", _conn)) { _cmd.Parameters.AddWithValue("@NAME", domainName); using (MySqlDataReader _read = _cmd.ExecuteReader()) { while (_read.Read()) { var _d = new Subdomain(); _d.Domain = DataExtensions.GetColumnValue <string>(_read, "domain"); _d.Login = DataExtensions.GetColumnValue <string>(_read, "login"); _d.Password = DataExtensions.GetColumnValue <string>(_read, "password"); _d.Name = DataExtensions.GetColumnValue <string>(_read, "name"); _d.UserType = DataExtensions.GetColumnValue <string>(_read, "sys_user_type"); _tmp.Add(_d); } } } _conn.Close(); } return(_tmp); }
public void RifreeeshReserved() { try { conn.Open(); String query = "SELECT t.id, t.total_amt, t.trans_date, t.status FROM client_transaction t INNER JOIN branch b ON t.branch_id = b.id WHERE date(trans_date) = CURDATE() AND branch_id = " + GlobalVariables.User_Branch_ID + ""; MySqlCommand comm = new MySqlCommand(query, conn); MySqlDataAdapter adp = new MySqlDataAdapter(comm); DataTable dt = new DataTable(); adp.Fill(dt); conn.Close(); reservedGrid.DataSource = dt; reservedGrid.Columns["id"].HeaderText = "Transaction ID"; reservedGrid.Columns["total_amt"].HeaderText = "Total Amount"; reservedGrid.Columns["trans_date"].HeaderText = "Transaction Date"; reservedGrid.Columns["status"].HeaderText = "Status"; } catch (Exception ee) { MessageBox.Show(ee.ToString()); conn.Close(); } }
public void insert_plan(string plan, int times) { DateTime dt = DateTime.Now; string day = dt.ToShortDateString().ToString(); day = day.Replace('/', '-'); string conn = "server=36.26.66.176;database=myplan;Character Set=utf8;Uid=myplan;password=myplan"; string sql = String.Format("insert into fzx_plan(plan, times,day) values('{0}',{1},'{2}')", plan, times, day); MySqlConnection myconn = new MySqlConnection(conn); try { myconn.Open(); MySqlCommand myCmd = new MySqlCommand(sql, myconn); if (myCmd.ExecuteNonQuery() > 0) { //MessageBox.Show("数据插入成功!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public bool CreateAndDropTable(String sql) { try { if (MySqlConnection.State == ConnectionState.Open) { try { MySqlCommand.CommandText = sql; MySqlCommand.ExecuteNonQuery(); } catch (Exception) { throw; } return(true); } return(false); } catch (Exception) { throw; } }
public int GlobalExecuteNonQuery(string executeSql, bool transaction, CommandType commandType, string[] parameters, object[] values, string[] outputParameters, object[] outputValues) { int result = -1; MySqlCommand sqlCommand = new MySqlCommand(executeSql, globalConnection); sqlCommand.Connection = globalConnection; sqlCommand.CommandText = executeSql; sqlCommand.CommandTimeout = commandTimeout; sqlCommand.CommandType = commandType; try { if (transaction) { sqlCommand.Transaction = globalConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted); } FillParameters(sqlCommand, parameters, values, outputParameters, outputValues); result = sqlCommand.ExecuteNonQuery(); if (transaction) { sqlCommand.Transaction.Commit(); } return(result); } catch { if (transaction) { sqlCommand.Transaction.Rollback(); } throw; } }
private void Open1() { try { using (MySqlConnection con = new MySqlConnection(ConstantLib.BasicConn_Real)) { using (MySqlCommand cmd = new MySqlCommand("domabiz.USP_GM11_POP01_SELECT_01", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("i_sdate", MySqlDbType.VarChar, 10); cmd.Parameters[0].Value = dt1F.EditValue3; cmd.Parameters.Add("i_edate", MySqlDbType.VarChar, 10); cmd.Parameters[1].Value = dt1T.EditValue3; using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd)) { DataTable ds = new DataTable(); sda.Fill(ds); efwGridControl3.DataBind(ds); this.efwGridControl3.MyGridView.BestFitColumns(); } } } //lbCount.Text = String.Format("{0:#,##0}", Convert.ToInt32(gridView1.RowCount)); } catch (Exception ex) { MessageAgent.MessageShow(MessageType.Error, ex.ToString()); } }
private void opop1() { string connectionString = @"" + Settings.Default.packingConnectionString + ""; using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); string time = DateTime.Now.ToString("dd"); int GG = Convert.ToInt32(yan3); GG++; using ( MySqlCommand cmd = new MySqlCommand("UPDATE packing.dones_smena SET smena1 = " + GG + " WHERE project ='" + Properties.Settings.Default.project + "'" + " AND id='" + odi + "' AND referencia='" + Properties.Settings.Default.referencia + "' AND dates='" + DateTime.Now.ToString("dd.MM.yyyy") + "';", conn)) { cmd.ExecuteNonQuery(); reader = cmd.ExecuteReader(); int i = 0; //try //{ while (reader.Read()) { odi = reader[0].ToString(); } //} //catch (Exception) //{ //} } } }
private void crystalReportViewer1_Load(object sender, EventArgs e) { cn.Open(); MySqlCommand cmd = new MySqlCommand("select * from shop_pay ", cn); ReportDocument crystalreport = new ReportDocument(); DataTable ds6 = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter(cmd); da.Fill(ds6); crystalreport.Load(@"E:\Metro use\Metro use\report_payment_history.rpt"); crystalreport.SetDataSource(ds6); crystalReportViewer1.ReportSource = crystalreport; cn.Close(); }
private void carregarCliente(int idCli) { try { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = Conexao.Connection; cmd.CommandText = @"select * from cliente where id_cli =@id"; cmd.Parameters.AddWithValue("@id", idCli); Conexao.Conectar(); var reader = cmd.ExecuteReader(); string telefone = "", fone, ddd; while (reader.Read()) { txtId.Text = reader["id_cli"].ToString(); txtNome.Text = reader["nom_cli"].ToString(); txtEmail.Text = reader["email_cli"].ToString(); ddlStatus.SelectedItem.Value = reader["stt_cli"].ToString(); telefone = reader["des_numero_cli"].ToString(); int numMax = telefone.Length - 2; ddd = telefone.Substring(0, 2); fone = telefone.Substring(2, numMax); txtDdd.Text = ddd; txtFone.Text = fone; } } catch (Exception ex) { string erro = ex.Message; } finally { Conexao.Desconectar(); } }
public Int32 Obtener_Ultima_EncS1008() { int i = 0; MySqlCommand comando = new MySqlCommand("select max(idS1008_Com) as Contador from S1008_Com", conex); comando.CommandTimeout = 12280; DataSet ds = new DataSet(); MySqlDataAdapter Adapter = new MySqlDataAdapter(); Adapter.SelectCommand = comando; Adapter.Fill(ds); DataTable tabla = new DataTable(); tabla = ds.Tables[0]; DataRow row = tabla.Rows[0]; i = Convert.ToInt32(row["Contador"]); if (i == 0) { Error error = new Error("", 41); errores.Add(error); } return(i); }
//Insert statement public void Insert(string rfidFields, string dateUpload,string amount, string eventA, string dateEnd) { string query = "INSERT INTO logfilepaypal(RFID_Nr,DateAndTime_file_upload,Amount,Event_Account,DateAndTim_file_end) VALUE('" +rfidFields + "','" + dateUpload + "','"+Convert.ToInt32(amount) + "','" + eventA + "','" + dateEnd + "')"; /*query += rfidFields + "','" + dateUpload + "','"+amount + "','" + eventA + "','" + dateEnd + "'";*/ //INSERT INTO logfilepaypal(RFID_Nr,DateAndTime_file_upload,Amount,Event_Account,DateAndTim_file_end) VALUES('2300fb4525','2014-10-07 16:13:03',1000,'fontys12345','2014-11-07 16:14:25'); //c = new ClientInfo(rfidFields, dateUpload, amount, eventA, dateEnd); //string query = c.ToString(); //open connection if (this.OpenConnection() == true) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, connection); //Execute command //Used to execute a command that will not return any data, for example Insert, update or delete. cmd.ExecuteNonQuery(); //close connection this.CloseConnection(); } }
public void addGrade(Grade grade) { MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString; myConnectionString = "server=localhost;uid=root;pwd=;database=db1;"; try { conn = new MySql.Data.MySqlClient.MySqlConnection(); conn.ConnectionString = myConnectionString; conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.CommandText = "insert into grade(studentID, teacherID, grade_value, course) values (" + "'" + grade.student_id + "'," + "'" + grade.teacher_id + "'," + grade.grade_value + ',' + "'" + grade.course + "')"; cmd.ExecuteNonQuery(); conn.Close(); } catch (MySql.Data.MySqlClient.MySqlException ex) { Console.Write(ex.Message); } }
private void buttonPirkti_Click(object sender, EventArgs e) { DB db = new DB(); MySqlCommand command = new MySqlCommand("INSERT INTO `bilietai`(`renginio_id`, `vartotojo_id`, `vieta`, `eile`, `kiekis`) VALUES (@renginio_id, @vartotojo_id, @vieta, @eile, @kiekis)", db.getConnection()); command.Parameters.Add("@renginio_id", MySqlDbType.VarChar).Value = renginys.RenginioId; command.Parameters.Add("@vartotojo_id", MySqlDbType.VarChar).Value = vartotojo_id; command.Parameters.Add("@vieta", MySqlDbType.VarChar).Value = Convert.ToInt32(listBoxVieta.GetItemText(listBoxVieta.SelectedItem)); command.Parameters.Add("@eile", MySqlDbType.VarChar).Value = Convert.ToInt32(listBoxEile.GetItemText(listBoxEile.SelectedItem)); command.Parameters.Add("@kiekis", MySqlDbType.VarChar).Value = Convert.ToInt32(listBoxKiekis.GetItemText(listBoxKiekis.SelectedItem)); db.openConnection(); if (command.ExecuteNonQuery() == 1) { MessageBox.Show("Bilietas nupirkas ir išsiustas jums į El.paštą!", "Bilietas nupirktas", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("ERROR"); } }
public void deleteGrade(int grade_id) { MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString; myConnectionString = "server=localhost;uid=root;pwd=;database=db1;"; try { conn = new MySql.Data.MySqlClient.MySqlConnection(); conn.ConnectionString = myConnectionString; conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.CommandText = "delete from grade where id=" + grade_id; cmd.ExecuteNonQuery(); conn.Close(); } catch (MySql.Data.MySqlClient.MySqlException ex) { Console.Write(ex.Message); } }
private string bxbookusersOku() { //uye olan kullanıcının kullanici idsini elde eder. string userID = " "; MySqlConnection users = new MySqlConnection(baglanti); users.Open(); //UyeOl sayfasından gelen verileri alıyoruz. int UyeOlKulaniciID = UyeOl.gonderilecekveri; string mysqlusers = "SELECT * FROM `tbl_bxusers`"; MySqlCommand cmdusers = new MySqlCommand(mysqlusers, users); MySqlDataReader rdrusers = cmdusers.ExecuteReader(); while (rdrusers.Read()) { if (rdrusers["kullanicibilgileriID"].ToString() == UyeOlKulaniciID.ToString()) { userID = rdrusers["idKullanici"].ToString(); } } return userID; }
public void updateGrade(Grade grade) { MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString; myConnectionString = "server=localhost;uid=root;pwd=;database=db1;"; try { conn = new MySql.Data.MySqlClient.MySqlConnection(); conn.ConnectionString = myConnectionString; conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.CommandText = "update grade set studentID='" + grade.student_id + "',grade_value=" + grade.grade_value + ", course='" + grade.course + "' where id=" + grade.id; cmd.ExecuteNonQuery(); conn.Close(); } catch (MySql.Data.MySqlClient.MySqlException ex) { Console.Write(ex.Message); } }
public string CardNumberRandom() { string no; string checkCard; DataBaseConnection db = new DataBaseConnection(); MySqlDataReader readData; do { System.Random x = new Random(); no = x.Next(1, 10000).ToString(); string dbRequest = "SELECT card FROM user WHERE card = '" + no + "'"; MySqlCommand command = new MySqlCommand(dbRequest, db.connToDb); if (db.connToDb.State == System.Data.ConnectionState.Closed) { db.connToDb.Open(); } using (readData = command.ExecuteReader()) { if (readData.HasRows) { readData.Read(); checkCard = readData.GetString("card"); } else { checkCard = "0"; } } }while (no == checkCard); db.connToDb.Close(); return(no); }
public DataSet get(string __query, [Optional] MySqlParameter[] __param) { this.command = new MySqlCommand(__query, this.connection); if (__param != null) { this.command.Parameters.AddRange(__param); } this.dAdapter = new MySqlDataAdapter(this.command); this.dSet = new DataSet(); /* input exemplo: 'SELECT * FROM tabela WHERE id = @id' * output: 'FROM tabela' */ Regex rgx = new Regex("FROM\\s\\w+"); MatchCollection matches = rgx.Matches(__query); /* output: 'tabela' */ string table = matches[0].Value.Replace("FROM ", ""); this.dAdapter.Fill(this.dSet, table); return(this.dSet); }
// Método para finalizar a venda // esse método faz um select pelo codigo da venda e muda o status da venda para RECEBIDO apos a confirmação de recebimento public void FinalizarVenda(Pedido pedido) { try { AbrirConexao(); Cmd = new MySqlCommand("UPDATE pedido SET valor_total_pedido = @valorTotal, situacao = 2 WHERE id_pedido = @idPedido", Con); Cmd.Parameters.AddWithValue("idPedido", pedido.Id_Pedido); Cmd.Parameters.AddWithValue("@valorTotal", pedido.Total_Venda); Cmd.ExecuteNonQuery(); //MessageBox.Show("Venda realizada com sucesso.", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception erro) { throw erro; } finally { FecharConexao(); } }
private void excluirToolStripMenuItem_Click(object sender, EventArgs e) { try { conexao cn = new conexao(); MySqlConnection sqlc = new MySqlConnection(cn.conn); sqlc.Open(); String SQL = "Delete From CadastroFuncionarios Where IDFuncionario = @ID"; MySqlCommand cmd = new MySqlCommand(SQL, sqlc); cmd.Parameters.Add("@ID", MySqlDbType.Int16).Value = DgConsulta.SelectedCells[0].Value.ToString(); cmd.ExecuteNonQuery(); MessageBox.Show("Dados Excluidos com Sucesso!!"); btnConsultarFuncionarios_Click(sender, e); } catch (Exception Erro) { MessageBox.Show(Erro.Message); } }
public int SetLabels(Player player, int balance) { int uid = Login.userId; DB db = new DB(); MySqlDataAdapter adapter = new MySqlDataAdapter(); db.OpenConnection(); MySqlCommand command = new MySqlCommand("SELECT * FROM users WHERE id = @uid", db.GetConnection()); command.Parameters.Add("@uid", MySqlDbType.VarChar).Value = uid; using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string PlayerCurrency = reader.GetString("user_credits"); String returnString = player.mylbl.Text= "Your balance:" + PlayerCurrency.ToString(); return Convert.ToInt32(PlayerCurrency); } } //in case of an error return 0; }
public Boolean MtdActualizarGenero(ClsEGenero objCar) { try { ClsConexion Objconexion = new ClsConexion(); MySqlCommand ObjCommand = new MySqlCommand(); ObjCommand.Connection = Objconexion.conectar(); ObjCommand.CommandText = "usp_E_ModificarGenero"; ObjCommand.CommandType = CommandType.StoredProcedure; ObjCommand.Parameters.Add(new MySqlParameter("Acod", MySqlDbType.VarChar)); ObjCommand.Parameters.Add(new MySqlParameter("Anom", MySqlDbType.VarChar)); ObjCommand.Parameters["Acod"].Value = objCar.codgen; ObjCommand.Parameters["Anom"].Value = objCar.nomgen; ObjCommand.Connection = Objconexion.conectar(); ObjCommand.ExecuteNonQuery(); return(true); } catch (Exception ex) { return(false); throw ex; } }