Enumeration Type JDBC

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Enumeration Type JDBC

This Java example program introduce enumeration type with JDBC.

[edit] Java Source Code

  • Package: matthews.mark
  • File: EnumTesting.java
package matthews.mark;
 
/*
 
 MySQL and Java Developer's Guide
 
 Mark Matthews, Jim Cole, Joseph D. Gradecki
 Publisher Wiley,
 Published February 2003, 
 ISBN 0471269239
 
 */
//Modified by Code Panda, http://java.exampleshow.com
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class EnumTesting {
    Connection connection;
 
    Statement statement;
 
    public EnumTesting() {
	try {
	    Class.forName("com.mysql.jdbc.Driver").newInstance();
	    connection = DriverManager
		    .getConnection("jdbc:mysql://localhost/exampleshow?user=root&password=123321");
	} catch (Exception e) {
	    System.err.println("Unable to find and load driver");
	    System.exit(1);
	}
    }
 
    public void doWork() {
	try {
	    statement = connection.createStatement();
	    ResultSet rs = statement
		    .executeQuery("SHOW COLUMNS FROM pet LIKE 'name'");
 
	    rs.next();
	    String enums = rs.getString("Type");
	    System.out.println("Type="+enums);
	    int position = 0, count = 0;
	    String[] availableEnums = new String[10];
 
	    while ((position = enums.indexOf("'", position)) > 0) {
		int secondPosition = enums.indexOf("'", position + 1);
		availableEnums[count++] = enums.substring(position + 1,
			secondPosition);
 
		position = secondPosition + 1;
		System.out.println(availableEnums[count - 1]);
	    }
 
	    rs.close();
	    statement.close();
	    connection.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
 
    public static void main(String[] args) {
	EnumTesting e = new EnumTesting();
	e.doWork();
    }
}

[edit] What Result You Can Get

Run the program, you will get:


Type=varchar(100)

[edit] Required External Library for this Java Example

In order to run this example program, the following library is needed:

and you need to create a Database, name it exampleshow, and create a table, name it pet, with the following SQL scripts:

CREATE TABLE pet (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(100) DEFAULT NULL,
  PRIMARY KEY  (id)
); 
 
 
INSERT INTO pet VALUES (1,'Dog');
INSERT INTO pet VALUES (2,'Cat');
INSERT INTO pet VALUES (3,'Panda');


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools