1、首先登陆mysql,查看mysql的数据情况,select * from test_data1 t
2、新建java类,测试jdbc功能
3、编写java的jdbc代码,
String driver = "com.mysql.cj.jdbc.Driver"
String url = "jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8&useSSL=false"
String user = "root"
String pwd = "123456"
4、代码中查询mysql数据表,并执行查出表中内容;select * from test_data1
import java.sql.*public class MysqlTest {
public static void main(String[] args){
// 驱动程序名
String driver = "com.mysql.jdbc.Driver"
// URL指向要访问的数据库名world
String url = "jdbc:mysql://127.0.0.1:3306/world"
// MySQL配置时的用户名
String user = "root"
// MySQL配置时的密码
String password = "123456"
String name
try {
// 加载驱动程序
Class.forName(driver)
// 连续数据库
Connection conn = DriverManager.getConnection(url, user, password)
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!")
// statement用来执行SQL语句
Statement statement = conn.createStatement()
// 要执行的SQL语句
String sql = "select * from city"
// 结果集
ResultSet rs = statement.executeQuery(sql)
while(rs.next()) {
// 选择Name这列数据
name = rs.getString("Name")
// 输出结果
System.out.println(rs.getString("CountryCode") + "\t" + name)
}
rs.close() conn.close() }
catch(ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!")
e.printStackTrace()
} catch(SQLException e) {
e.printStackTrace()
} catch(Exception e) {
e.printStackTrace()
}
}
}
String driverName = "com.mysql.jdbc.Driver" // 加载JDBC驱动String dbURL = "jdbc:mysql://localhost:3306/test" // 连接服务器和数据库test
String userName = "sa" // 默认用户名
String userPwd = "sa" // 密码
java.sql.Connection dbConn
try {
Class.forName(driverName).newInstance()
dbConn = java.sql.DriverManager.getConnection(dbURL, userName, userPwd)
System.out.println("Connection Successful!") //如果连接成功 控制台输出Connection Successful!
} catch (ClassNotFoundException e) {
System.out.println("没有找到驱动")
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace()
}
还是直接上代码吧。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)