首页 > 编程知识 正文

怎么连接数据库,sql数据库

时间:2023-05-03 17:26:44 阅读:142836 作者:1414

package com.lee.javaweb.mvc;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

公共类link MySQL {

publicstaticvoidmain (string [ ] args ) {

声明连接对象

连接连接器;

//驱动程序名称

string driver=' com.MySQL.JDBC.driver ';

//URL是要访问的数据库名称mydata

string URL=' JDBC : MySQL ://localhost :3306/test ';

//MySQL配置时的用户名

String user='root ';

//MySQL配置时的密码

String password='123456 ';

//遍历查询结果集

try {

//加载驱动程序

class.forname(driver;

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

con=driver manager.getconnection (URL,user,password );

if (! con.isClosed () )

system.out.println (succeededconnectingtothedatabase! ' );

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

statement statement=con.create statement (;

//要执行的SQL语句

string SQL=' select * fromstudenttable ';

//3 .包含检索到的结果集的resultset类!

resultset RS=statement.execute query (SQL;

system.out.print ln (---------);

System.out.println ('执行结果如下: );

system.out.print ln (---------);

System.out.println (姓名((() ) )职务);

system.out.print ln (---------);

string job=空;

string id=空;

wile(RS.next ) ) }

获取名为stuname的列的数据

job=RS.getstring(student_name );

获取名为stuid的列的数据

id=RS.getstring(location );

//输出结果

system.out.println(id't'job;

}

rs.close (;

con.close (;

}catch(classnotfoundexceptione ) )

//数据库驱动系统的异常处理

system.out.println(Sorry,can ) tfindthedriver! ' );

e .打印任务跟踪(;

}catch(sqlexceptione ) {

//数据库连接失败异常处理

e .打印任务跟踪(;

}catch(exceptione ) {

//TODO: handle exception

e .打印任务跟踪(;

}finally{

System.out.println (数据库数据获取成功! ' );

}

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。