java连接mysql-1

安装jdk(包括jre)并配置路径和测试

安装mysql

1、mysql-5.5.12-win32.msi

2、设置密码,其余默认

3、运行测试

show databases;

show tables;

 

安装apache(可不选)

1、使用压缩版,解压出来

2、配置JAVA_HOME和JAVA_JRE

3、运行bin下startup.bat,开启服务;shutdown.bat关闭服务

 

连接器

1、获得mysql-connector-java-5.1.15-bin.jar

2、在classpath中添加它的路径

 

创建应用程序

1、建立文件ConnectMysql.java,内容如下 

import java.io.*;
import java.sql.*;
public class ConnectMysql 
{
	private String DBDriver="com.mysql.jdbc.Driver";
	private String url="jdbc:mysql://localhost:3306/test";
	public Connection conn=null;
	public ResultSet rs=null;
	public Statement stmt=null;
	
	public ConnectMysql()
	{
		try
		{
			Class.forName(DBDriver);
		}
		catch(java.lang.ClassNotFoundException e)
		{
			System.out.println("jdbcDriver error!");
		}
	}
	public ResultSet query(String mySql)  throws SQLException
	{
		rs=null;
		try
		{
			//Class.forName(DBDriver);
			conn=DriverManager.getConnection(url,"root","xhp");//有可能出错
			stmt=conn.createStatement();
			rs=stmt.executeQuery(mySql);
		}
		catch(SQLException e)
		{
			System.out.print(e.getMessage());
		}
		return rs;
	}
	
	public void update(String mySql) throws Exception
	{
		stmt=null;
		try
		{
			//Class.forName(DBDriver);
			conn=DriverManager.getConnection(url,"root","xhp");//有可能出错
			stmt=conn.createStatement();
			stmt.executeUpdate(mySql);
		}
		catch(SQLException e)
		{
			System.out.print(e.getMessage());
		}
		finally
		{
			stmt.close();
			conn.close();
		}
	}
	
	public void closeStmt()
	{
		try
		{
			stmt.close();
		}
		catch(SQLException e)
		{
			System.err.println("closeStmt error");
		}
	}
	
	public void closeConn()
	{
		try
		{
			conn.close();
		}
		catch(SQLException e)
		{
			System.err.println("closeConn error");
		}
	}
	
	public static void main(String[] args)
	{
		ConnectMysql connMysql=new ConnectMysql();
		//String sql="select * from employee";
		String sql="select * from toupiao";
		try
		{
			ResultSet rs=connMysql.query(sql);
			while(rs.next()){
				System.out.print(rs.getString("no"));
				System.out.print("	"+rs.getString("name"));
				System.out.print("	"+rs.getString("age"));
				System.out.print("	"+rs.getString("gender"));
				System.out.print("	"+rs.getString("dept"));
				System.out.print(rs.getString("id"));
				System.out.print("	"+rs.getString("name"));
				System.out.println("	"+rs.getString("num"));
			}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			connMysql.closeStmt();
			connMysql.closeConn();
		}
	}
}
2、转到当前目录,javac ConnectMysql.java;java ConnectMysql

3、运行结果 

1       JSP     12
2       JSF     15
3       Structs 18

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值