java连接数据库的代码

java连接数据库的代码,第1张

package mysql

import java.sql.*

/**

* @author xys

*/

public class ConnectMysql {

public static Connection getConnection() throws ClassNotFoundException, SQLException {

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

String user = "mysqluser"

String password = "password"

String driverClass = "com.mysql.cj.jdbc.Driver"

Connection connection = null

Class.forName(driverClass)

try {

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

} catch (SQLException e) {

e.printStackTrace()

}

if (connection != null) {

System.out.println("数据库连接成功")

} else {

System.out.println("数据库连接失败")

connection.close()

}

return connection

}

public void getResult() throws ClassNotFoundException, SQLException {

// 实例化 Statement 对象

Statement statement = getConnection().createStatement()

// 要执行的 Mysql 数据库 *** 作语句(增、删、改、查)

String sql = ""

// 展开结果集数据库

ResultSet resultSet = statement.executeQuery(sql)

while (resultSet.next()) {

// 通过字段检索

int id = resultSet.getInt("id")

String name = resultSet.getString("name")

// 输出数据

System.out.println("ID : " +id)

System.out.println("name :" + name)

}

// 完成后需要依次关闭

resultSet.close()

statement.close()

getConnection().close()

}

}

try{

class.forName(driver)

}

catch (ClassNotFoundException e)

{

e.printStackTrace()

}

错了,应该写在方法里面。。。

public Connection getConnection()

{

try{

class.forName(driver)

connection = DriverManager.getConnection(URL,username,password)

}

catch (SQLException e1)

{

e1.printStackTrace()

}

catch (ClassNotFoundException e)

{

e.printStackTrace()

}

return connection

}

或者把他放在构造方法里。

当然是:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

编译肯定不对。


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

原文地址:https://54852.com/sjk/9630382.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存