Eclipse中写Java代码实现Java连接MYSQL数据库

Eclipse中写Java代码实现Java连接MYSQL数据库,第1张

import java.sql.*

public class DataBasePractice {

public static void main(String[] args) {

//声明Connection对象

Connection con

//驱动程序

String driver = "com.mysql.jdbc.Driver"

//URL指向要访问的数据库名mydata

String url = "jdbc:mysql://localhost:3306/mydata"

//MySQL配置时的用户名

String user = "root"

//MySQL配置时的密码

String password = "root"

//遍历查询结果集

try {

//加载驱动程序

Class.forName(driver)

//1.getConnection()方法,连接MySQL数据库!!

con = DriverManager.getConnection(url,user,password)

if(!con.isClosed())

System.out.println("Succeeded connecting to the Database!")

//2.创建statement类对象,用来执行SQL语句!!

Statement statement = con.createStatement()

//要执行的SQL语句

String sql = "select * from student"

//3.ResultSet类,用来存放获取的结果集!!

ResultSet rs = statement.executeQuery(sql)

System.out.println("-----------------")

System.out.println("执行结果如下所示:")

下面是一段正确的代码,如果配置没有问题,可以直接运行,希望可以帮到你,顺便一提,数据库如果设置有问题,是无法使用的,你可以在网上看看如何配置数据库。

import java.sql.Connection 

import java.sql.DriverManager 

import java.sql.SQLException 

public class ConnectionDemo02{

// 定义MySQL的数据库驱动程序,需根据自己情况更改

public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" 

// 定义MySQL数据库的连接地址,需根据自己情况更改

public static final String DBURL = "jdbc:mysql://localhost:3306/mldn" 

// MySQL数据库的连接用户名,需根据自己情况更改

public static final String DBUSER = "root" 

// MySQL数据库的连接密码,需根据自己情况更改

public static final String DBPASS = "mysqladmin" 

public static void main(String args[]){

Connection conn = null   // 数据库连接

try{

Class.forName(DBDRIVER)  // 加载驱动程序

}catch(ClassNotFoundException e){

e.printStackTrace() 

}

try{

conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) 

}catch(SQLException e){

e.printStackTrace() 

}

System.out.println(conn)  // 如果此时可以打印表示连接正常

try{

conn.close()   // 数据库关闭

}catch(SQLException e){

e.printStackTrace() 

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6173655.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-17
下一篇 2023-03-17

发表评论

登录后才能评论

评论列表(0条)

保存