How do I add a value to my database?

1

I need that, if the value is null, it would add the variable getid() to the database.

string comando = "SELECT COUNT(*) FROM usuarios WHERE username=@Usuario AND senha=@Senha AND tipo=1";
var connection = new MySqlConnection(connString);
var cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("@Usuario", usuario);
cmd.Parameters.AddWithValue("@Senha", senha);
var command = connection.CreateCommand();
connection.Open();
MySqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
    hd_id = leitor["id"].ToString();
}
if (hd_id == null)
{
    //Código aqui
}
int retorno = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
    
asked by anonymous 07.06.2017 / 15:26

1 answer

0

To redeem only 1 value, you do not necessarily need to use the reader, to get straight from ExecuteScalar(); . To do the insertion of getid() , I would have to do an update, the way I did, see if it fits you well.

The code, I got yours as a base, although it is not well written.

string comando = "SELECT id FROM usuarios WHERE username=@Usuario AND senha=@Senha AND tipo=1";
var connection = new MySqlConnection(connString);
var cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("@Usuario", usuario);
cmd.Parameters.AddWithValue("@Senha", senha);
connection.Open();
string id = cmd.ExecuteScalar().ToString();
if (id == "" || id == null)
{
    string update = "UPDATE usuarios SET id=@getid WHERE username=@Usuario";
    cmd = new MySqlCommand(update, connection);
    string gid = getid();
    cmd.Parameters.AddWithValue("@getid", gid);
    cmd.ExecuteScalar();
}
    
07.06.2017 / 15:38