driver=com.mysql.jdbc.Driver url=jdbc\:mysql\://localhost/test?useUnicode\=true&characterEncoding\=gb2312 user=root password=root
import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnectionUtils { private static String[] getProperty() throws IOException { String[] properties = new String[4]; Properties props = new Properties(); props.load(ConnectionUtils.class.getClassLoader().getResourceAsStream( "db.properties")); String driver = props.getProperty("driver"); String url = props.getProperty("url"); String user = props.getProperty("user"); String password = props.getProperty("password"); properties[0] = driver; properties[1] = url; properties[2] = user; properties[3] = password; return properties; } public static Connection getConnection() throws SQLException, IOException, ClassNotFoundException { String[] properties = getProperty(); Class.forName(properties[0]); return DriverManager.getConnection(properties[1], properties[2], properties[3]); } }
import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnectionUtils { private static String[] getProperty() throws IOException { String[] properties = new String[4]; Properties props = new Properties(); props.load(ConnectionUtils.class.getClassLoader().getResourceAsStream( "db.properties")); String driver = props.getProperty("driver"); String url = props.getProperty("url"); String user = props.getProperty("user"); String password = props.getProperty("password"); properties[0] = driver; properties[1] = url; properties[2] = user; properties[3] = password; return properties; } public static Connection getConnection() throws SQLException, IOException, ClassNotFoundException { String[] properties = getProperty(); Class.forName(properties[0]); return DriverManager.getConnection(properties[1], properties[2], properties[3]); } }
本文提供了一个简单的Java程序示例,展示了如何使用Java的MySQL JDBC驱动程序连接到本地MySQL数据库,并通过配置文件加载数据库连接参数。程序演示了如何获取驱动类、建立数据库连接、设置属性和执行SQL查询。
3113

被折叠的 条评论
为什么被折叠?



