Sample code for connecting to MySQL database

Hi:

I am learning to use Eclipse.

Are there some sample projects available to
illustrate connecting to a SQL database ?

Thanks,
Phil Miller
pillmillAsked:
Who is Participating?
 
ctamrakarCommented:
ye you could also get this info.
 String url = "jdbc:mysql://" + ip-address + ":" + database_port + "/" + mysqldb_name;
 
from a properties file or config files  so that its independent of driver/db



0
 
fargoCommented:
0
 
Mayank SAssociate Director - Product EngineeringCommented:
It doesn't matter whether you use Eclipse or not ;-)

See the JDBC tutorial: http://java.sun.com/docs/books/tutorial/

For MySQL, select the DB and download the driver from:

http://developers.sun.com/product/jdbc/drivers
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
avinthmCommented:
Hi ,

You need to learn JDBC for this.
this link can help you to know abt JDBC
http://en.wikipedia.org/wiki/JDBC

some sample code....
http://java.sun.com/products/jdbc/reference/codesamples/index.html



cheers
0
 
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
http://www.developer.com/java/data/article.php/3417381

check out this link it has explanation in detail too.
0
 
ctamrakarCommented:
// consider mysqlConn is global variable and declared , you need a jdbc driver for mysql and put in classpath

Connection mysqlConn=null;

// sample method to connect to mysql

public void mySQLConnection() throws SQLException {
    if (mysqlConn == null) {
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      String url = "jdbc:mysql://" + ip-address + ":" + database_port + "/" + mysqldb_name;

      mysqlConn = DriverManager.getConnection(url, mysql_user, mysql_password);
      // set autocommit false
      mysqlConn.setAutoCommit(false);
    }
  }
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> DriverManager.registerDriver(new com.mysql.jdbc.Driver());

Its better to use Class.forName () and provide the driver-name as a String (read it from a properties-file or a configuration-file) so that the code is independent of the driver/ DB being used. Even better to use a data-source.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
I think this had to be a split.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.