Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Moderatore di ASP e MS Server L'avatar di Roby_72
    Registrato dal
    Aug 2001
    Messaggi
    19,559

    [C#] Query SELECT prima di INSERT INTO

    Salve, con il codice sottostante effettuo un inserimento:

    codice:
        MySql.Data.MySqlClient.MySqlConnection objConn;
        MySql.Data.MySqlClient.MySqlCommand objCmd;
        String strConnString, strSQL;
    
        strConnString = "Server=localhost;User Id=xxxxx; Password=xxxxx; Database=xxxx_it; Pooling=false";
        objConn = new MySql.Data.MySqlClient.MySqlConnection(strConnString);
        objConn.Open();
    
        strSQL = "INSERT INTO tnewsletter_tracking (newsletter_id,utente_id) VALUES (" + newsletter_id + "," + utente_id + ")";
    
        objCmd = new MySql.Data.MySqlClient.MySqlCommand(strSQL, objConn);
    
        try
        {
            objCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    
        objCmd = null;
        objConn.Close();
        objConn = null;
    Avrei la necessità di controllare che ciò che sto tentando di inserire non sia già presente nel db, quindi far precedere la INSERT da:
    codice:
    strSQL = "SELECT COUNT(*) FROM tnewsletter_tracking WHERE newsletter_id =" + newsletter_id + " AND utente_id = " + utente_id + "";
    Solo se la COUNT è 0 deve effettuare la query di inserimento.
    Come aggiungere nel codice la nuova query?

    Grazie.

  2. #2
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    il codice di sotto lo devi trattare come pseudo codice perchè è in basic e si riferisce ad Access
    codice:
    Option Strict On
    Imports l = libreria.ModuloWeb
    
    Partial Class prove_b
        Inherits System.Web.UI.Page
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim Connessione As OleDbConnection = Nothing
            Dim Comando As OleDbCommand = Nothing
            Dim Transazione As OleDbTransaction = Nothing
            Dim Sql As String = ""
    
            Try
                Connessione = New OleDbConnection(StringaConnessioneTest)
                Connessione.Open()
                Transazione = Connessione.BeginTransaction()
                Comando = New OleDbCommand
                Comando.Connection = Connessione
                Comando.Transaction = Transazione
    
                Append(Comando)
    
                'Transazione.Commit()
                Transazione.Rollback()
    
                l.MsgBox(Me, "Operazioni su database eseguite regolarmente")
    
    
            Catch ex As Exception
                If (Not (Transazione Is Nothing) AndAlso Not (Transazione.Connection Is Nothing)) Then Transazione.Rollback()
                l.MsgBox(Me, ex)
    
            Finally
                If (Not (Connessione Is Nothing)) Then Connessione.Close()
            End Try
    
        End Sub
    
    
        Private Sub Append(ByVal Comando As OleDbCommand)
            'simulo la lettura di id da un TextBox
            Dim id As String = "1"
    
            'controllo se già esistente
            Dim sql As String = "select count(*) from [campi] where [id] = ?"
            Dim n As Integer = CInt(msole.RisultatoAggregazioneSQL(Comando, sql, msole.createParameterInteger("id", id)))
    
            If n <> 0 Then
                Throw New Exception("id già esistente")
            End If
    
            sql = "INSERT INTO [CAMPI] ([ID]) VALUES (?) "
            Comando.CommandText = sql
    
            Comando.Parameters.Clear()
    
            Comando.Parameters.Add("id", OleDbType.Integer).Value = l.StringNullToDBNull(id)
    
            Comando.ExecuteNonQuery()
    
        End Sub
    
    
    
    End Class
    una versione di overload di RisultatoAggregazioneSQL è
    codice:
        Public Function RisultatoAggregazioneSQL(ByVal Comando As o.OleDbCommand, ByVal stringaSQL As String, ByVal ParamArray Parametri() As o.OleDbParameter) As Object
            Try
                Comando.CommandText = stringaSQL
                Comando.Parameters.Clear()
                For Each Parametro In Parametri
                    Comando.Parameters.Add(Parametro)
                Next
    
    
                RisultatoAggregazioneSQL = Comando.ExecuteScalar()
    
            Catch er As Exception
                Throw
            Finally
    
            End Try
    
        End Function
    in pratica
    apro la connessione (una volta per più operazione perchè è abbastanza onerosa)
    apro una transazione
    faccio quello che voglio, tipicamente aggiornamenti su più tabelle
    commit se non errore altrimenti Rollback
    chiudo la connessione

    Pietro

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.