This site requires JavaScript, please enable it in your browser!
Greenfoot back
vaibhav1988
vaibhav1988 wrote ...

2013/10/25

Connect To Database

vaibhav1988 vaibhav1988

2013/10/25

#
hello everyone, can any one tell me following: 1) Is it possible to connect greenfoot game with database. 2) if possible please give me the code.
Gevater_Tod4711 Gevater_Tod4711

2013/10/25

#
1. It is possible to connect java with a e.g. MySQL database. I think it should also work with greenfoot. 2. That unfortunately is not so easy. There are some librarys to connect to databases. You should have a look at the JDBC Tutorial by Oracle. I can give you some code I used once in a project (not greenfoot) but I don't think that you can use it easily.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import data.QuestionNaire;

public class dbConnection {
	
	Connection connection;
	
	String dbName;
	String tableName;
	
	public dbConnection(String dbUrl, String userName, String password, String driver/*, String dbName*/) throws Exception {
		//this.dbName = dbName;
		System.out.println("starting connection");
		Class.forName(driver);
		System.out.println("driver loaded");
		connection = DriverManager.getConnection(dbUrl, userName, password);
	}
	
	public void finalize() {
		try {
			shutdown();
		}
		catch (SQLException se) {
			se.printStackTrace();
		}
	}
}
This is a bit of standard code for a database connection. But there is much more you need to know. You should start with the tutorial. You also have to make clear that your database has the right values to connect to it. In my case the code didn't work because I had not the rights that were neccessary to read or writh from/in the database.
vaibhav1988 vaibhav1988

2013/10/26

#
thank you, but sorry to interrupt you this is the way we can connect to database using JDBC for servelet etc. but how to connect database in greenfoot that's was my question.
Gevater_Tod4711 Gevater_Tod4711

2013/10/26

#
I think this would work the same way. I don't know if there's another way without using the JDBC. But I also don't know why the JDBC should not work in Greenfoot.
You need to login to post a reply.