How do I add a value to my database?

Asked

Viewed 44 times

1

I need that if the value is null, it adds 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();
  • To which you are using the return variable?

  • it serves to return if the connection has been made for sure

  • getid() would be the id of the user’s insertion if the user is not found in the database?

  • What’s the problem? although I see some problems in the code? what you need to do?

  • @Andrewpaes no, it is an allegorical value.

1 answer

0


To redeem only 1 value, you do not necessarily need to use Reset, da para pegar direto do ExecuteScalar();. To insert the getid(), would have to do an update, the way I did, see if it fits you well.

The code, I took yours as the basis, although it’s 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.