Visualizzazione dei risultati da 1 a 5 su 5
  1. #1
    Utente di HTML.it L'avatar di jspippo
    Registrato dal
    Jul 2005
    Messaggi
    358

    asp.net e mysql inserimento record

    Ciao

    mi sto addentrando da poco con ASP.net e non riesco a capire come inserire un record in un db msyql.

    Ho sempre utilizzato asp e qua sembra tutto differente

    Il codice che sto usando è questo:

    <%@ Page Language="VB" Debug="true" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.SQLClient" %>


    <%
    Dim myConn as OdbcConnection
    Dim tbServer = "xx.xx.xx.xx"
    Dim tbDB = "xx"
    Dim tbLogin = "xx"
    Dim tbPwd = "xx"
    myConn = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver};SERVER="+tbServer+";PORT=3306;DATABASE="+t bDB+";USER="+tbLogin+";PASSWORD="+tbPwd+";OPTION=3 ;")

    myConn.Open()



    Response.Write("Connessione aperta con successo!")
    ' myConn.Close()

    %>

    <script language="VB" runat="server">
    Sub Page_Load(Source as Object, E as EventArgs)
    Dim InsertCommand As SqlCommand = New SqlCommand()
    InsertCommand.Connection = myConn
    Dim sql As String
    sql = "INSERT INTO pippo (oggetto) VALUES ('oggetto')"
    InsertCommand.CommandText = sql
    Try
    'myConn.Open()
    InsertCommand.ExecuteNonQuery()
    Catch ex As Exception
    response.Write(ex.ToString())
    Finally
    myConn.Close()
    End Try
    end sub
    </script>

    Come risultato mi da la classica pagina di errore di .net. Dimenitcavo, la connessione pare che vada a buon fine. Il provider è aruba sul quale ho altri lavori fatti con asp+mysql e che funzionano bene.

    Cosa c'è da sapere? dove sto sbagliando?

    Grazie a tutti

  2. #2
    guest.1
    Guest
    ciao, ti posto un esempio preso dal mio sito.
    Ricordati che se vedi delle sessioni perchè prima ho fatto i login, e il testo per inserire uso tiny_mce.
    Ora ti posto il codice, ovio che cambierai i campi:
    aggiungi.aspx
    codice:
    <%@ Page Title="" Language="C#" MasterPageFile="~/Admin/MasterPage.master" validateRequest="false" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.Odbc" %>
    <%@ Import Namespace="System.Configuration" %>
    <script runat="server">
        String connectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    
        Funzioni ut = new Funzioni();
        
        
        
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                    
                    txtNick.Text = "" + Session["User"] + "";
                    txtEmail.Text = "" + Session["Email"] + "";
    
            }
             
        }
    
        protected void DropDownList1_Init(object sender, EventArgs e)
        {
    
            OdbcConnection conn = new OdbcConnection(connectionString);
    
            string SQL = "SELECT * FROM news_category";
    
            OdbcCommand objCommand = new OdbcCommand(SQL, conn);
            conn.Open();
            OdbcDataReader ddlValues;
            ddlValues = objCommand.ExecuteReader();
    
            DropDownList1.DataSource = ddlValues;
            DropDownList1.DataValueField = "nCatId";
            DropDownList1.DataTextField = "cName";
            DropDownList1.DataBind();
            conn.Close();
        }
    
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                OdbcConnection objConn = new OdbcConnection(connectionString);
                objConn.Open();
                string sSQL = "INSERT INTO news (cCatId,_name,";
                sSQL = sSQL + "_email,";
                sSQL = sSQL + "_category,";
                sSQL = sSQL + "_subject,";
                sSQL = sSQL + "_contentHome,";
                sSQL = sSQL + "_content,";
                sSQL = sSQL + "_data,";
                sSQL = sSQL + "_status)VALUES(";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?,";
                sSQL = sSQL + "?)";
                OdbcCommand cmd = new OdbcCommand(sSQL, objConn);
                cmd.Parameters.AddWithValue("?", "" + DropDownList1.SelectedItem.Value + "");
                cmd.Parameters.AddWithValue("?", "" + txtNick.Text + "");
                cmd.Parameters.AddWithValue("?", "" + txtEmail.Text + "");
                cmd.Parameters.AddWithValue("?", "" + DropDownList1.SelectedItem.Text + "");
                cmd.Parameters.AddWithValue("?", "" + txtSubject.Text + "");
                cmd.Parameters.AddWithValue("?", "" + txtHomePage.Text + "");
                cmd.Parameters.AddWithValue("?", "" + txtMsg.Text + "");
                cmd.Parameters.AddWithValue("?", "" + txtDatePub.Text + "");
                cmd.Parameters.AddWithValue("?", "" + DDLock.SelectedItem.Value + "");
    
                cmd.ExecuteNonQuery();
                objConn.Close();
                Response.Redirect("default.aspx");
            }
            catch (System.Exception exc)
            {
                lblMsg.Text = "" + exc.ToString() + "";
            }
        }
    </script>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
         <script type="text/javascript" src="/jscripts/tiny_mce/tiny_mce.js"></script><script type="text/javascript">
            tinyMCE.init({
                // General options
                mode: "textareas",
                theme: "advanced",
                plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
    
                // Theme options
                theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
                theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
                theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
                theme_advanced_toolbar_location: "top",
                theme_advanced_toolbar_align: "left",
                theme_advanced_statusbar_location: "bottom",
                theme_advanced_resizing: true,
    
                // Example content CSS (should be your site CSS)
                content_css: "css/content.css",
    
                // Drop lists for link/image/media/template dialogs
                template_external_list_url: "lists/template_list.js",
                external_link_list_url: "lists/link_list.js",
                external_image_list_url: "lists/image_list.js",
                media_external_list_url: "lists/media_list.js",
    
                // Replace values for the template plugin
                template_replace_values: {
                    username: "Some User",
                    staffid: "991234"
                }
            });
    </script></asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <table width="100%" border="0">
      <tr>
        <td width="25%"></td>
        <td style="width:52%;"> 
            <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
          </td>
        <td width="75%"></td>
      </tr>
      <tr>
        <td width="25%">Categoria</td>
        <td style="width:52%;"> <asp:DropDownList ID="DropDownList1" runat="server" oninit="DropDownList1_Init">
           </asp:DropDownList></td>
        <td width="75%"></td>
      </tr>
      <tr>
        <td>Titolo</td>
        <td style="width:52%;">   <asp:TextBox ID="txtSubject" runat="server" Width="499px"></asp:TextBox></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                         ControlToValidate="txtSubject" ErrorMessage="RequiredFieldValidator" 
                         ValidationGroup="All">Richiesto Titolo</asp:RequiredFieldValidator></td>
      </tr>
      <tr>
        <td>Home Page</td>
        <td style="width:52%;"> <asp:TextBox ID="txtHomePage" runat="server" Width="499px" TextMode="MultiLine"></asp:TextBox></td>
        <td> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                         ControlToValidate="txtHomePage" ErrorMessage="RequiredFieldValidator" 
                         ValidationGroup="All">Richiesto Home page</asp:RequiredFieldValidator></td>
      </tr>
      <tr>
        <td>Messaggio</td>
        <td style="width:52%;">  <asp:TextBox ID="txtMsg" runat="server" Width="499px" TextMode="MultiLine"></asp:TextBox>
    </td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                         ControlToValidate="txtMsg" ErrorMessage="RequiredFieldValidator" 
                         ValidationGroup="All">Richiesto Messaggio</asp:RequiredFieldValidator></td>
      </tr>
      <tr>
        <td>Nick</td>
        <td style="width:52%;"><asp:TextBox ID="txtNick" runat="server"></asp:TextBox></td>
        <td> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" 
                         ControlToValidate="txtNick" ErrorMessage="Inserire Nome Utente" 
                         ValidationGroup="All"></asp:RequiredFieldValidator></td>
      </tr>
      
      <tr>
        <td>Email</td>
        <td style="width:52%;"> <asp:TextBox ID="txtEmail" runat="server" Width="188px"></asp:TextBox></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" 
                         ControlToValidate="txtEmail" ErrorMessage="Inserire Email" 
                         ValidationGroup="All"></asp:RequiredFieldValidator></td>
      </tr>
      <tr>
        <td>Dara Ora Pubblicazione</td>
        <td style="width:52%;"> <asp:TextBox ID="txtDatePub" runat="server"></asp:TextBox></td>
        <td> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
                ControlToValidate="txtDatePub" ErrorMessage="Errore scrivere data 00/00/0000" 
                ValidationExpression="^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$" ValidationGroup="All"></asp:RegularExpressionValidator>
            <asp:CompareValidator ID="CompareValidator1" ControlToValidate="txtDatePub" Operator="DataTypeCheck"  Type="date" runat="server" ErrorMessage="*Errore"></asp:CompareValidator>
     </td>
      </tr>
      <tr>
        <td>Stato di pubblicazione</td>
        <td style="width:52%;"> <asp:DropDownList ID="DDLock" runat="server" AutoPostBack="True">
        <asp:ListItem Value="0">N</asp:ListItem>
        <asp:ListItem Value="1">Y</asp:ListItem>
        </asp:DropDownList></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" 
                         ControlToValidate="DDLock" ErrorMessage="Inserire Stato" ValidationGroup="All"></asp:RequiredFieldValidator>
       </td>
      </tr>
      <tr>
        <td></td>
        <td style="width:52%;"> 
            <asp:Button ID="btnAdd" runat="server" Text="Aggiungi" 
            onclick="btnAdd_Click" ValidationGroup="All" /></td>
        <td> </td>
      </tr>
      </table></asp:Content>

  3. #3
    guest.1
    Guest
    scusa, ma mi son scordato una cosa:
    nel web.config:
    codice:
    	<appSettings />
    	<connectionStrings>
        <add name="ConnStr" connectionString="Driver={MySQL ODBC 3.51 Driver}; Server=ipremote; Uid=tuouser; Pwd=tuapassword; Database=tuodatabase;" />
      </connectionStrings>

  4. #4
    Utente di HTML.it L'avatar di jspippo
    Registrato dal
    Jul 2005
    Messaggi
    358
    Ciao, prima di tutto grazie di aver risposto.

    Il problema è che dovrei integrare lo script per l'inserimento in un'altro scritto in vb...quindi questo in c# non credo vada bene...

    Ora vedrò di trovare un'altra soluzione, grazie lo stesso.

  5. #5
    guest.1
    Guest
    cerca su google, c to vb.net
    il primo link c'è il convertitore.

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.