Create a simple connection with mysql

hello
my name is edvanio i am from brazil.
i'd like to connect one program in Java with mysql for insert, delete and update one simple base ex. teste with nome and fone.
thank , bye

here's a couple of sites
http://www.javacoding.net/articles/technical/java-mysql.html
http://www.developer.com/java/data/article.php/3417381
I recently installed MySQL (just to see if I could get a working program to run)
these were the steps
1. downloaded MySQL
2. downloaded the connector file
3. unzipped/installed MySQL
4. unzipped the connector file
mysql-connector-java-3.0.17-ga-bin.jar
copied the jar file into this directory
C:\Program Files\Java\jdk1.5.0_03\jre\lib\ext
5. opened MySQL, using the code from Gamelan
create the db JunkDB
created the user, permissions, password
6. combined the code from both sites (code follows)
and it worked OK
import java.sql.*;
class MySQL_Test
  public MySQL_Test() throws Exception
    testDriver();
    Connection con = getConnection();
    executeUpdate(con,"CREATE TABLE test(id int,text varchar(20))");
    executeUpdate(con,"insert into test(id,text) values (1,'first entry')");
    executeUpdate(con,"insert into test(id,text) values (2,'second entry')");
    executeUpdate(con,"insert into test(id,text) values (3,'third entry')");
    executeQuery(con,"select * from test");
    executeUpdate(con,"drop table test");
    con.close();
  protected void testDriver() throws Exception
    try
      Class.forName("com.mysql.jdbc.Driver");
      System.out.println("MySQL Driver found");
    catch(ClassNotFoundException cnfe)
      System.out.println("OOPs - MySQL Driver nowhere to be found");
      throw (cnfe);
  protected Connection getConnection() throws Exception
    String url = "";
    try
      url = "jdbc:mysql://localhost:3306/JunkDB";
      Connection con = DriverManager.getConnection(url,"auser","drowssap");
      System.out.println("Connection OK");
      return con;
    catch(SQLException sqle)
      System.out.println("OOPs - No Connection");
      throw (sqle);
  protected void executeUpdate(Connection con,String sqlStatement) throws Exception
    try
      Statement s = con.createStatement();
      s.execute(sqlStatement);
      s.close();
    catch(SQLException sqle)
      System.out.println("OOPs - error executing statement");
      throw (sqle);
  protected void executeQuery(Connection con,String sqlStatement) throws Exception
    try
      Statement s = con.createStatement();
      ResultSet rs = s.executeQuery(sqlStatement);
      while(rs.next())
        String id = (rs.getObject("id").toString());
        String text = (rs.getObject("text").toString());
        System.out.println("Found record "+id+" "+text);
      rs.close();
    catch(SQLException sqle)
      System.out.println("OOPs - error executing resultset");
      throw (sqle);
  public static void main(String[] args)
    try
      new MySQL_Test();
    catch(Exception e){e.printStackTrace();}
}

Similar Messages

  • Create database connection with Mysql

    Hi, all:
    inside JDeveloper, i try to create a database connection for Mysql (third party
    JDBC driver). I input all needed parameters into
    JDeveloper database connection dialog, and test connection, the error message
    says 'Unable to find driver org.gjt.mm.mysql.Driver". The jar file contains driver
    is listed in system classpath, and Mysql and MM-Mysql JDBC driver are tested with
    other applications and there is no problem.
    So, what i should do to create such a connection ??
    Any help will be appreciated. thank you in advance.
    kevin.

    The connectio URL could look like this:
    (leave the User-, Password-, and Role-fields, in the tab before, empty)
    Java Class Name: org.gjt.mm.mysql.Driver
    URL: jdbc:mysql://localhost:3306/test?ultradevhack=true&?user=myuser&?password=mypassword

  • Creating a TCP connection with SSL/TLS

    Hi,
    I am working in a application that depends on the server. I need to estabilish a TCP connection with SSL/Tls secure connection with the server in order to get the datas.
    I have the following code structure :
    - (id)initWithHostAddressNSString*)_host andPortint)_port
    [self clean];
    self.host = _host;
    self.port = _port;
    CFWriteStreamRef writeStream;
    CFReadStreamRef readStream;
    return self;
    -(BOOL)connect
    if ( self.host != nil )
    // Bind read/write streams to a new socket
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDef ault, (CFStringRef)self.host, self.port, &readStream, &writeStream);
    return [self setupSocketStreams];
    - (BOOL)setupSocketStreams
    // Make sure streams were created correctly
    if ( readStream == nil || writeStream == nil )
    [self close];
    return NO;
    // Create buffers ---- has not been released , so need to check possible ways to release in future
    incomingDataBuffer = [[NSMutableData alloc] init];
    outgoingDataBuffer = [[NSMutableData alloc] init];
    // Indicate that we want socket to be closed whenever streams are closed
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    //Indicate that the connection needs to be done in secure manner
    CFReadStreamSetProperty(readStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
    // We will be handling the following stream events
    CFOptionFlags registeredEvents = kCFStreamEventOpenCompleted |
    kCFStreamEventHasBytesAvailable | kCFStreamEventCanAcceptBytes |
    kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
    // Setup stream context - reference to 'self' will be passed to stream event handling callbacks
    CFStreamClientContext ctx = {0, self, NULL, NULL, NULL};
    // Specify callbacks that will be handling stream events
    BOOL doSupportAsync = CFReadStreamSetClient(readStream, registeredEvents, readStreamEventHandler, &ctx);
    BOOL doSupportAsync1 = CFWriteStreamSetClient(writeStream, registeredEvents, writeStreamEventHandler, &ctx);
    NSLog(@"does supported in Asynchrnous format? : %d :%d", doSupportAsync, doSupportAsync1);
    // Schedule streams with current run loop
    CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    // Open both streams
    if ( ! CFReadStreamOpen(readStream) || ! CFWriteStreamOpen(writeStream))
    // close the connection
    return NO;
    return YES;
    // call back method for reading
    void readStreamEventHandler(CFReadStreamRef stream,CFStreamEventType eventType, void *info)
    Connection* connection = (Connection*)info;
    [connection readStreamHandleEvent:eventType];
    // call back method for writing
    void writeStreamEventHandler(CFWriteStreamRef stream, CFStreamEventType eventType, void *info)
    Connection* connection = (Connection*)info;
    [connection writeStreamHandleEvent:eventType];
    `
    As above, I have used
    CFReadStreamSetProperty(readStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3);
    in order to make a secured connection using sockets.
    The url i am using is in the format "ssl://some domain.com"
    But in my call back method i am always getting only kCFStreamEventErrorOccurred for CFStreamEventType .
    I also tried with the url "https://some domain.com" ,but getting the same error.
    i also commented out setting kCFStreamPropertySocketSecurityLevel, but still i am receiving the same error that i mentioned above.
    I dont know how it returns the same error. I have followed the api's and docs , but they mentioned the same way of creating a connection as i had given above.
    I tried to get the error using the following code :
    CFStreamError error = CFWriteStreamGetError(writeStream);
    CFStreamErrorDomain errDomain = error.domain;
    SInt32 errCode = error.error;
    The value for errCode is 61 and errDomain is kCFStreamErrorDomainPOSIX. so i checked out the "errno.h", it specifies errCode as "Connection refused"
    I need a help to fix this issue.
    If the above code is not the right one,
    **(i)how to create a TCP connection with SSL/TLS with the server.**
    **(ii)How the url format should be(i.e its "ssl://" or "https://").**
    **(iii)If my above code is correct where lies the error.**
    I hope the server is working properly. Because I can able to communicate with the server and get the datas properly using BlackBerry and android phones. They have used SecuredConnection api's built in java. Their url format is "ssl://" and also using the same port number that i have used in my code.
    Any help would be greatly appreciated.
    Regards,
    Mohammed Sadiq.

    Hello Naxito. Welcome to the Apple Discussions!
    Try the following ...
    Perform a "factory default" reset of the AX
    o (ref: http://docs.info.apple.com/article.html?artnum=108044)
    Setup the AX
    Connect to the AX's wireless network, and then, using the AirPort Admin Utility, try these settings:
    AirPort tab
    o Base Station Name: <whatever you wish or use the default>
    o AirPort Network Name: <whatever you wish or use the default>
    o Create a closed network (unchecked)
    o Wireless Security: Not enabled
    o Channel: Automatic
    o Mode: 802.11b/g Compatible
    Internet tab
    o Connect Using: Ethernet
    o Configure: Manually
    o IP address: <Enter your college-provided IP address>
    o Subnet mask: <Enter your college-provided subnet mask IP address>
    o Router address: <Enter your college-provided router IP address>
    o DNS servers: <Enter your college-provided DNS server(s)
    o WAN Ethernet Port: Automatic
    <b>Network tab
    o Distribute IP addresses (checked)
    o Share a single IP address (using DHCP & NAT) (enabled)

  • External connection with MYSQL db

    Hi to all,
    i need to make an external connection to MYSQL database with "EXEC SQL" instruction of abap/4.
    I've already maintained the DBCON table: i've created a new external connection (called TEST1), but i don't really know how to valorize the DBMS (db type) and CON_ENV (connection instructions) fields .
    For MSSQL is simple (there are many examples on this forum), but for MYSQL db?? I wasn't able to find posts about configuring it.
    Is there this kind of connection possible. What are other "way" to make this connection? I'd like to select/insert/update some table rows
    Helpfull answer will surely good rewarded
    Thx a lot in Advice
    Andrea Galluccio

    Hi
    For MSSQL , we give the Connection Information as just MSSQL_SERVER=<ServerName>. But for MYSQL and oracle the parameters differ.
    Just check out http://www.irietools.com/iriepascal/progref125.html
    I am not quite sure abt it.

  • Problem in establishing connection with mysql 5.0

    Hi,
    I am using JCAPS 5.1. I tried to insert data to mysql database table.
    But i got following error
    java.sql.SQLException: Error in allocating a connection. Cause:
    Physical Connection doesn't exist.
    My intention is to read file in which data are comma seperated and to
    populate those values to a mysql 5.0 database table.
    Sample DATA in file [test.txt]
    111,gg,23,MFG
    112,hh,24,MFG
    113,ii,25,RETAIL
    114,jj,26,IT
    Database table: employee
    eno,ename,eage,edept
    While creating JDBC OTD there is no problem in establishing connection with database. But after deploying i got above error.
    I have used Mysql 5.0 Connector/J JDBC driver. Added JDBC driver jar files to following directories as required.
    1) C:\JavaCAPS51\logicalhost\is\lib
    2)C:\JavaCAPS51\logicalhost\is\domains\test\lib
    Steps i have followed as per JDBC-ODBC -eway user guide doc.
    1) Created USerDefined OTD and added necessary fields
    2) Created JDBC OTD.
    3) Created JAVA collaboration and do business process for inserting
    4) Mapped all components by creating in Connectivity MAp
    5) created necessary external systems in envrionment explorer.[JDBC External System and File External System]
    6)Created Deployment profile
    5) Deployed it.
    After deploying it gives error as
    java.sql.SQLException: Error in allocating a connection. Cause: Physical Connection doesn't exist
    Please let me know the solution for problem.
    Message was edited by:
    VenkateshSampoornam

    In the environment definition,
    -> External Application JDBC
    -> Properties
    -> Outbound JDBC Connection
    You have the database URL in the "DriverProperties" field
    Valid URL would be : jdbc:mysql://localhost:3306/caps
    !! The doc says that this field is optional !! Seems to be an error in the doc:
    Hope this helps
    Seb

  • Problem in creating a CMP bean with MySql

    Hi,
    I am using lomboz eclipse, jboss 4.0.2, xdoclet 1.2.3 & DB as MySql 5.0. I am encountering a very strange problem when I try to create a CMP with MySql as DB. After entering relevant information about the datasource & testing the connection & finding it to be successful, I get the error in lomboz eclipse as : CMP has no attributes. Moreover, I donot even get the table names from the schema, that was given in the datasource, with which the mapping of my CMP will be done.
    I tried using Oracle 9i. But to my wonder, I didnot experience this issue, as it gave me all the CMP atttributes mapped & also created the CMP with Oracle DB. Can anyone help me in getting this issue resloved with MySql DB?

    Yeah, the DB User permissions are found to be ok, as the test connection was successfull. I have tried for MySql 4.1 & Myql 5.0, with their respective jars & driver classes. But the result was same. Test connection is successful, but when i hit the next button to see the CMP attributes, it doesnot give me the list of tables under that schema & says that CMP has no attributes. Please help.

  • Connecting with mysql

    hello
    how can i create a connection to mysql and postgresql databases in jdbc. without using odbc.
    thanks.

    You need to use a different driver. I assume you're using the jdbc-odbc bridge driver.
    For mysql, get the mm.mysql driver at http://mmmysql.sourceforge.net/
    For postgresql, go to http://jdbc.postgresql.org/
    I've only used the mysql driver, so I don't know the details of how to use the postgresql one.
    In general, you will have to do the following:
    1. download the jar file and put it in your classpath
    2. change the connection url string to conform with the format in the driver documentation.

  • Problem with USERNAME & PASSWORD creation--JDBC connection with MYSQL

    How to connect to JDBC with Mysql Connector
    i installed mysql & created table, it works fine
    During Password---> I gave it as tiger , no username
    i installed mysql connector
    i saved the .jar file path in class path
    HOW TO CREATE USERNAME & PASSWORD & DATASOURCE NAME ---> Is it the password -tiger or something else like (ADMinstrative tools-ODBC-services--etc )
    Pl, help,
    tks
    Xx

    How to connect to JDBC with Mysql Connector
    i installed mysql & created table, it works fine
    During Password---> I gave it as tiger , no usernameTiger? This ain't Oracle.
    I think you should give a username and password. How can it look up a password without a username? Better GRANT the right permissions, too.
    Read the MySQL docs a bit more closely. Your path isn't the way to go.
    %

  • Java connection with mysql

    Anybody please help me:
    I creating java application that comunicate with the mysql database. I use JConnector and all work find.
    My problem is when i compile the program into JAR file and when i run it(double click the file), i saw my application but the connection with the mysql database is not successfull. i try to search from internet, and i found that i must put my JConnector inside the jdk1.3.1/jre/lib/ext.
    Once i put that the program can run and the connection is fine, but only if i run it from the dos by typing the command c:\java -jar turkeySystem.jar.
    So anybody can advise me, what should i do if i want to make my application run smoothly and connected with the database, without having the dos run at the background. (just double click the jar file).
    i don't have problem to run that if i using ms access as a database.
    Thank you in advanced.

    if it runs with "java -jar turkeySystem.jar." you have a valid manifest.mf in your jar. so it can basically be executed by double clicking it --- if the JDK is installed correctly. otherwise you need to change the datatype handling in windows by adding "java -jar %1" as the command for the file suffix ".jar". this is the case if you e.g. just copy your Java SDK folder to a computer and didn't install it with the windows exe java wizard.

  • How to create a data connection with dynamic XML file?

    Thanks for all reply first!
    I have formatted the submitted data into an XML file on the server side,this file can be import to PDF form correctly.
    I try to send this XML file to the user to let him can review what he has submitted.
    I guess that I should create a data connection to the XML file so that it can be reviewed by the user.
    But the question is that the XML file is dynamic generated.
    How can i do?
    give me some clus or examples,please.
    thanks,
    Jasper.

    Hi Jasper,
    To show user back the result, you can use PDF instead of XML. You can store the PDF template in server and you can merge XML data with PDF template by Livecycle Form Data Integration service.
    We, as KGC, can generate huge number of Adobe Livecycle forms in small periods. Also we give consultancy on Adobe Livecycle ES products and Adobe Livecyle Designer. In case of any need, do not hesitate to contact us.
    Asiye Günaydın
    Project Consultant
    KGC Consulting Co.
    www.kgc.com.tr

  • Connectivity with MySQL in Windows

    How can I connect JSP with MySQL in Windows?
              I Tried out the following code but It did not work
              Class.forName("org.gjt.mm.mysql.Driver");
              Connection cn = DriverManager.getConnection("jdbc:mysql:///test");
              

    I think you missed the IP address for your MySQL server machine.
              If it's on the same computer, try this:
              jdbc:mysql://localhost/test
              "John Jacob" <[email protected]> wrote in message
              news:[email protected]..
              > How can I connect JSP with MySQL in Windows?
              > I Tried out the following code but It did not work
              >
              > Class.forName("org.gjt.mm.mysql.Driver");
              > Connection cn = DriverManager.getConnection("jdbc:mysql:///test");
              

  • How connect with mysql 5

    hi master
    sir i am use studio creator now i install the mysql5
    sir please give me idea how i connect my studio creator with mysql 5
    thank
    aamir

    hi
    follow the following steps:
    1) Download Jconnector Driver for java from www.mysql.com
    2) Open the creator , from servers palette select data source and right click.
    3) choose new data source , click new
    4) select the jar file u downloaded from the web site.
    5)clicj suggeste ( this will make the creator to select connections statments automatailcly )
    6) put the username and password and click ok
    this will make a datasource with mysql server.
    be sure that the mysql server is run,, and make sure that u apply right username and password
    Hope this will help
    Good luck
    Mohammed

  • Jar file connection with mysql

    Hello everyone i ve a problem if you people could solve please help...
    When i compile my java code with mysql connection it works perfectly, but when i convert into jar file its not updating any values in the mysql database
    Can anyone tell me a solution.

    subhavenkatesh wrote:
    Can anyone tell me a solution.You have a bug. Find it. Fix it.

  • I want to create a simple docuement with 2 pages?

    I want to my plugin to create a simple document as soon as My Plugin is loaded in Indesign. I have derived my class IStartupShutdownService  so that it's called in startup.
    But this is failing at line 23 below.
    What else do I need to include in my .fr file?
    class LTestStartupShutdownServiceImpl : public CPMUnknown<IStartupShutdownService>
    public:
        LTestStartupShutdownServiceImpl(IPMUnknown* boss);
        virtual ~LTestStartupShutdownServiceImpl();
        virtual void Startup();
        virtual void Shutdown();
    CREATE_PMINTERFACE(LTestStartupShutdownServiceImpl, kLTestStartupShutdownServiceImpl)
    LTestStartupShutdownServiceImpl::LTestStartupShutdownServiceImpl(IPMUnknown *boss):CPMUnknown<IStartupShutdownService>(boss)
        do
            const PMReal width=612, height=792;
            const int32 numPages=5, numPagesPerSpread=1;
            // Create the command.
            InterfacePtr<ICommand> newDocCmd(Utils<IDocumentCommands>()->CreateNewCommand());  //<-----this is coming null and failing
            ASSERT(newDocCmd);
            if (newDocCmd == nil)
                break;
            // Set the command's parameterised data.
            InterfacePtr<INewDocCmdData> newDocCmdData(newDocCmd, UseDefaultIID());
            ASSERT(newDocCmdData);
            if (newDocCmdData == nil)
                break;
            newDocCmdData->SetCreateBasicDocument(kFalse); // Override the following defaults.
            PMPageSize pageSize( width, height);
            newDocCmdData->SetNewDocumentPageSize(pageSize);
            bool16 bWide = kTrue; // landscape orientation.
            newDocCmdData->SetWideOrientation(bWide);
            // Size margin proportional to document width and height.
            PMReal horMargin = width / 20;
            PMReal verMargin = height / 20;
            newDocCmdData->SetMargins(horMargin, verMargin, horMargin, verMargin);
            newDocCmdData->SetNumPages(numPages);
            newDocCmdData->SetPagesPerSpread(numPagesPerSpread);
            // Create the new document.
            CmdUtils::ProcessCommand(newDocCmd);
        while (false);
    LTestStartupShutdownServiceImpl::~LTestStartupShutdownServiceImpl()
    void LTestStartupShutdownServiceImpl::Startup()
    void LTestStartupShutdownServiceImpl::Shutdown()
    Below is the .fr file:
    * Boss class definitions.
    resource ClassDescriptionTable(kSDKDefClassDescriptionTableResourceID)
    Class
      kLTestStartupShutdownServiceBoss,
      kInvalidClass,
      // Implementation of IStartupShutdownService
      IID_ISTARTUPSHUTDOWN, kLTestStartupShutdownServiceImpl,
      // Implementation to IK2ServiceProvider to identify the service type as startup-shutdown
      IID_IK2SERVICEPROVIDER, kLTestStartupShutdownServiceImpl,

    Hi maddy,
    I want to save the document to MyDocuments folder, I tried to look in IDocFileHandler but I can not get a function which takes path/name as input with docRef.
    Can u suggest how can my document to disk?
    I dont want user to enter any detail, the document just created should get saved on Disk with the use of some commands only.

  • Automatically create ODBC DSN connection with powershell or GPO

    Hi,
    I'm trying to create a ODBC connection that has a special network port and also password automatically stored.
    I have tried to do this with the add-odbcdsn cmdlet and adding attributes to a group policy object configuration without luck.
    If I try to export settings with regedit and import them trough logonscript, the normal users dont have user rights to the LOCAL Machine hive.
    Therefore I have tried to export a USER DSN instead, but either of the port or password settings are exported.
    Please help.

    Hello,
    You can create a VB Script (.vbs) as the one create by Clamp77 on the following thread.
    http://stackoverflow.com/questions/23552529/can-i-create-a-bat-file-to-automate-data-sources-adding-in-odbc-data-source-adm
    Then you can run the script on computers using GPOs as explained on the following article.
    http://technet.microsoft.com/en-us/library/dn789196.aspx
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

Maybe you are looking for

  • Animated GIF - Fastest frame rate?

    I am trying to create a sort of lightning effect and would like to flip through three or four frames super quickly (for the flash effect). Problem is that in my animation settings, even if i set the frame duration to 1/100, the frames still show for

  • Pricing in Service order

    We are into the business of Building products like manufacturing of aluminum. Doors & window. Once we sold this to the customers, we have to install also. Sometimes we have to charge from the customers & sometimes not. Installation takes a lot of tim

  • RuleFrame and BR's that should be handled the PRE or before triggers.

    When a business rule must be handled before INSERT/UPDATE/DELETE of an record, it looks to me like it cannot be implemented using a CAPI. For example the following BR: 'When value of column is NULL use default value retrieved from other column.' Do I

  • IPhone 6 stuck in landscape after unlock

    Most of the time when I unlock my phone, the open app is in landscape mode. It will not switch to portrait unless I rotate the phone 90 degrees to landscape and then back to portrait. This is extremely annoying on apps that have very discrepant funct

  • Lynx K3011 volume and Win8 Button no function in Windows 8

    Hi, I just got my brand-new Lynx tablet and have installed all Windows 8 updates. Everything works fine, exept the "Volume" and "Win8 Home" Button are without function. Do I have to install additional drivers? In the device Manager everything looks f