Java连接数据库

来源:互联网 发布:ubuntu怎么连无线 编辑:程序博客网 时间:2024/06/01 23:26

一、直接使用Driver类

public void testDriver(){//1.创建一个Driver 实现类的对象Driver driver=new com.mysql.jdbc.Driver();//2.准备连接数据库的基本信息:url,user,passwordString url="jdbc:mysql://localhost:3306/test";Properties info = new Properties();info.put("user", "root");info.put("password","1230");//3.调用Driver 接口的 connection(url,info)获取数据库连接Connection conn=driver.connect(url, info);System.out.println(conn);}

二、通过文件连接数据库

public Connection getConnection() throws Exception{String driverClass = null;String jdbcUrl = null;String user = null;String password = null;//读取类路径下的jdbc,properties文件InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");Properties properties=new Properties();properties.load(in);driverClass = properties.getProperty("driver");jdbcUrl = properties.getProperty("jabcUrl");user = properties.getProperty("user");password = properties.getProperty("password");//通过反射常见 Driver对象Driver driver=(Driver)Class.forName(driverClass).newInstance();Properties info = new Properties();info.put("user", user);info.put("password", password);//通过Driverd 的 connect 方法获取数据库连接Connection conn = driver.connect(jdbcUrl, info);return conn;}


三、通过DriverManager连接数据库


public static void testDriverManager() throws Exception {//1,准备连接数据库的4个字符串:驱动全类名、JDBC URL、user、passwordString driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";String jdbcUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=Ywpw";String user="zyj";String password="zyj";//2.加载数据库驱动程序(注册驱动)Class.forName(driverClass);Connection conn=DriverManager.getConnection(jdbcUrl, user, password);System.out.println(conn);}

四、连接各数据库的JDBCUrl

Mysql:jdbc:mysql://localhost:3306/数据库名

SQLServer:jdbc:sqlserver://localhost:1433;DatabaseName=数据库名

Oracle:jdbc:oracle:thin:@localhost:1521:orcl



原创粉丝点击