/*
* @author Mr Liu
* sql语句的连接基本步骤:
* 1、驱动程序名
* 2、URL指向要访问的数据库名Database
* 3、 MySQL配置时的用户名
* 4、MySQL配置时的密码
* 5、加载驱动程序
* 6、连续数据库
* 7、statement用来执行SQL语句
* 8、要执行的SQL语句
* 9、结果集
* 10、选择需要显示的这列数据
* 11、输出结果
*
*/
public class SqlConnection {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名Database
String url = "jdbc:mysql://127.0.0.1:3306/Liuzhi";
// MySQL配置时的用户名
String username = "root";
// MySQL配置时的密码
String password = "root";
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn = DriverManager.getConnection(url, username, password);
if (!conn.isClosed()) {
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
//要执行的SQL语句
String sql="select id,xm,username,passw from student";
//结果集
ResultSet result=statement.executeQuery(sql);
while(result.next()){
System.out.println(result.getString("xm"));
}
}
}
}
我的数据库:
输出结果: