1安装mysql数据库,参考点击打开链接
2安装完成后创建自己的数据库表和内容
3使用jdbc连接数据库,下载mysql关于jdbc的文件,在项目中添加相应的jar包和类,
在项目中建立语句连接数据库代码如下
import java.sql.*;
public class TestMysqlConnection {
/**
* @param args
*/
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while (rs.next()) {
System.out.println(rs.getString("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这样就可以在项目中使用创建的数据库了。