JAVA数据库编程,获得数据库连接

学习到数据库编程,给大家分享下数据库的驱动获取,及数据库的连接

import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.spi.DirStateFactory.Result;


public class Sql {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection conn=null;//数据库的连接
		java.sql.Statement stat=null;//数据库的操作Statment
		String sql[]={"create table student(id varchar(10),name varchar(10)",
				      "insert into student values('1','lv')",
				      "insert into student values('2,'htc')"};
		try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动
			System.out.println("驱动加载成功");
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		try {
			conn=DriverManager.getConnection("jdbc:mysql://localhost/student?user=root&password=123456");//连接数据库
			System.out.println("获得数据库连接");
			stat=conn.createStatement();
//逐个执行数据库语句
			for(int i=0;i<sql.length;i++)
			{
				stat.executeUpdate(sql[i]);
				System.out.println("第"+(i+1)+"次执行"+sql[i]+"语句");
				
			}
			System.out.println("执行完毕");
			
		} catch (SQLException e1) {
			// TODO: handle exception
			e1.printStackTrace();
		}
				

	}

}


你可能感兴趣的:(java数据库连接)