1 连接mysql数据库
package lianxi1; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.junit.Test; public class JdbcTest { @Test public void test1() throws Exception{ getConnection(); } // 1写入连接数据库的四个字符串 public Connection getConnection() throws Exception{ // 2 读取类路径下的jdbc.properites文件 InputStream is = getClass().getClassLoader().getResourceAsStream("jdbc.properties"); Properties pro = new Properties(); pro.load(is); String driver = pro.getProperty("driverClass"); String url = pro.getProperty("url"); String user = pro.getProperty("user"); String password = pro.getProperty("password"); //3 创建连接 Class.forName(driver); return DriverManager.getConnection(url, user,password); } }
jdbc.properties文件:
driverClass = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/test user = user password =1234