I created a database connection class that I want to use Thread
to make queries faster.
In functions ExecutarSelect
and ExecutarSQLPiece
I have returns, but I could not get those returns through the thread.
I did a search but could not get the solution, could someone help me?
Thank you very much!
// Instantiating and calling thread execution
ThreadBD thBD = new ThreadBD();
thBD.comandoSQL = "SELECT acessoRapido FROM dbo.parametrosUsuario";
Thread th = new Thread(thBD.executarSQLPiece);
th.Start();
// DataBase Connection Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Threading;
namespace H7Transporte
{
class ConexaoBD
{
//string connection;
DataTable tabela = new DataTable();
string retorno;
public ConexaoBD()
{
}
public void ExecutarQuery(string comandoString)
{
string connectionString = "Data Source=.\SQLServer;Initial Catalog=H7Transporte;Integrated Security=True";
SqlConnection cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand comando = new SqlCommand(comandoString, cnn);
comando.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Não foi possivel executar seu comando. O Query pode estar errado ou o retorno é nulo ");
}
finally
{
cnn.Close();
}
}
public DataTable ExecutarSelect(string comandoString)
{
string connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=teste2;Integrated Security=True";
SqlConnection cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlDataAdapter Preencher = new SqlDataAdapter(comandoString, cnn);
Preencher.Fill(tabela);
}
catch (Exception)
{
MessageBox.Show("Nenhuma informação foi encontrada. Seu Query pode estar errado ou o retorno é nulo ");
}
finally
{
cnn.Close();
}
return tabela;
}
public string sqlPiece(string comandoString)
{
string connectionString = "Data Source=.\SQLServer;Initial Catalog=H7Transporte;Integrated Security=True";
SqlConnection cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand comando = new SqlCommand(comandoString, cnn);
SqlDataReader sqlReader = comando.ExecuteReader();
sqlReader.Read();
retorno = sqlReader.GetValue(0).ToString();
}
catch (Exception)
{
MessageBox.Show("Nenhuma informação foi encontrada. Seu Query pode estar errado ou o retorno é nulo");
}
finally
{
cnn.Close();
}
return retorno;
}
}
class ThreadBD
{
public string comandoSQL { get; set; }
public string retorno { get; set; }
public void executarQuery()
{
ConexaoBD conecta = new ConexaoBD();
conecta.sqlPiece(comandoSQL);
}
public void executarSelect()
{
ConexaoBD conecta = new ConexaoBD();
conecta.sqlPiece(comandoSQL);
}
public void executarSQLPiece()
{
ConexaoBD conecta = new ConexaoBD();
conecta.sqlPiece(comandoSQL);
}
}
}