---
title: "java connect MySQL  "
author: "share112"
date: "2011-06-09T09:59:07Z"
tags: []
categories: ["编程语言"]
slug: "java-connect-mysql"
draft: false
lastmod: "2011-06-09T09:59:07Z"
id: 1073917
url: "https://share112.iteye.com/blog/1073917"
---

转自：[http://yuyinghan.blog.sohu.com/6666248.html](http://yuyinghan.blog.sohu.com/6666248.html)

 

 

1、中文化问题：由于mysql采用的默认编码为ISO8859-1,有的程序员称之为Latin-1或者ANSI,这就与java所采用的unicode产生了冲突，会出现在java对MySQL输入输出时出现乱码的问题。  
   我所采用的解决方案：  
   a.将从数据库提出的字符串数据进行ISO8859-1到GB2312的转换,这样就可以为java所用。  
     String name=result.getString("name");  
     name=new String(name.getBytes("ISO8859-1"),"gb2312");  
   b.将java的字符串数据进行GB2312到ISO8859-1的转换,这样就可以为MySQL所用。  
     name= new String(name.getBytes("gb2312"),"ISO8859-1");  
     stat.execute("INSERT INTO t1 VALUES('432','"+name+"')");

2、属性文件的建立：可以首先在磁盘中建立一个名为 database.properties的文件文件的内容如下：

jdbc.drivers=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://127.0.0.1:3306/test  
jdbc.username=root  
jdbc.password=\*\*\*\**

这样在代码中可利用该文件做为输入流，以建立Connection对象。

3、Connection对象的建立

public static Connection  getConnection() throws  
 SQLException ,IOException{  
  Properties props=new Properties();  
  FileInputStream in=new FileInputStream("database.properties");  
  props.load(in);  
  in.close();  
  String drivers=props.getProperty("jdbc.drivers");  
  if(drivers!=null) System.setProperty("jdbc.drivers",drivers);  
  String url=props.getProperty("jdbc.url");  
  String username=props.getProperty("jdbc.username");  
  String password=props.getProperty("jdbc.password");  
    
  return DriverManager.getConnection(url,username,password);   
 }

4、数据的提取和插入

 public static void main(String args\[]) throws Exception{  
  try{  
   Connection con=getConnection();  
   Statement stat=con.createStatement();  
   ResultSet result=stat.executeQuery("SELECT * FROM t1");  
   result.next();  
   System.out.println (result.getString(1));  
   String name=result.getString(2);  
   //编码转换  
   name= new String(name.getBytes("ISO8859-1"),"gb2312");  
   System.out.println (name);  
   

   String name1="张三";  
   System.out.println (name1);  
    //编码转换  
   name1= new String(name1.getBytes("gb2312"),"ISO8859-1");  
   stat.execute("INSERT INTO t1 VALUES('432','"+name1+"')");  
   stat.close();  
   con.close();  
  }  
  catch(Exception e){  
  }  
 }

&lt;script&gt;&lt;/script&gt;