数据库MySql8.0的连接创建与第一个实例

在电脑已经安装mysql, 以及相关的配置,然后下载Mysql连接驱动程序, 下载连接驱动程序.
把驱动程序导入应用程序中,步骤是在项目名上单击鼠标右键, 选择"build path",再选择“add External Archivers…”,再选择加载的驱动,驱动程序导入之后,在该项目下出现"Referenced Libraries"。

数据库连接类DBConnection.java:

package com.myjdbc;
import	java.sql.Connection;
import  java.sql.DriverManager;
import  java.sql.SQLException;

public class DBConnection {
	private String	driver = "com.mysql.cj.jdbc.Driver";
	private String conurl = "jdbc:mysql://localhost:3306/mydb?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT";
	private String username = "root";
	private String userpasswd = "123456";
	private Connection	connection = null;
	
	public Connection getConnection() {
		// TODO Auto-generated constructor stub
		try {
			Class.forName(driver);
			System.out.println("driver success!");

			connection = DriverManager.getConnection(conurl, username, userpasswd);
			System.out.println("Connection success!");
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
			System.out.println("driver failure!");
		}catch (SQLException e) {
			// TODO: handle exception
			System.out.println("connection failure!");
			e.printStackTrace();
		}
		return connection;
	}

	public void closeConnection(){
		if (connection != null)
		{
			try {
				connection.close();
				System.out.println("close database success!");
			} catch (SQLException e) {
				// TODO: handle exception
				System.out.println("close failure!");
			}
			
		}
		
	}
}

数据库表的创建CreateTable.java:

package com.myjdbc;
import	java.sql.Connection;
import  java.sql.SQLException;
import  java.sql.Statement;

public class CreateTable {
	private Connection con = null;
	private	Statement	stmt = null;
	
	public CreateTable() {
		// TODO Auto-generated constructor stub
	}
	
	public	boolean	createBookDataTable(){
		DBConnection onecon= new DBConnection();
		con = onecon.getConnection();
		boolean returnResult = true;
		
		try {
			 stmt = con.createStatement();
			String pSql = "create table student (sno char(10), sname char(20), sage integer, smajor char(10))";
			stmt.execute(pSql);
			stmt.close();	// 释放Statement 所连接的数据及JDBC资源
			con.close();	//关闭与数据库的链接
			
		} catch (SQLException e) {
			// TODO: handle exception
			returnResult = false;
			e.printStackTrace();
		}
		
		return returnResult;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			CreateTable	c = new CreateTable();
			boolean	isSuccess = c.createBookDataTable();
			if (isSuccess)
				System.out.println("The table is createed.");
			else {
				System.out.println("The table is not createed.");
			}
	}
}

运行程序结果为:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值