解决IDEA、Pycharm连接数据库乱码的问题

一、IDEA.

使用IDEA连接数据库:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* Created by test on 2017/11/18.
* 数据库连接
* 自己设置连接方式避免乱码
*/

public class my {
public static void main(String[] args) {
Connection con;
String driver="com.mysql.jdbc.Driver";
//这里我的数据库是test
//String url="jdbc:mysql://localhost:3306/test";
String user="*****";//使用名,未做修改默认是root
String password="******";//密码自己补充
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
try {
Class.forName(driver);
//con = DriverManager.getConnection(url, user, password);
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed()) {
System.out.println("数据库连接成功");
}
Statement statement = con.createStatement();
String sql = "select * from my;";/* 我的表格叫my */
ResultSet resultSet = statement.executeQuery(sql);
String name;
while (resultSet.next()) {
name = resultSet.getString("name");
System.out.println("姓名:" + name);
}
resultSet.close();
con.close();
} catch (ClassNotFoundException e) {
System.out.println("数据库驱动没有安装");

} catch (SQLException e) {
System.out.println("数据库连接失败");
}
}
}



二、Pycharm
"""
连接mysql的方法
#!/uer/bin/python3
@ datatime:2018/8/7
@ 连接mysql
@ user:******
@ secret:*******
@ grant来授权用户 在mysql中完成
@ UNcode = utf-8mb4 可以保存 或者是 utf-8
"""
import pymysql as py

"""
导入pymysql的模板
第一个参数主机名 或者主机地址
第二个参数 用户名
第三个参数密码
第四个参数数据库
"""
# 连接数据库
db = py.connect("localhost", "root(这是默认的)", "*****(密码)", "student(数据库)")
# 创建游标对象
cursor = db.cursor()
# 通过execute()方法执行SQL语句
sql = """
..........
........
.......
"""
cursor.execute(sql)
# 关闭数据库
db.close()


"""
第二种连接mysql数据库的方法
"""
import pymysql
config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'passwd': '123456',
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor
}
db = pymysql.connect(**config)
db.autocommit(1)
cursor = db.cursor()

这是3.6.+的pycharm,以及10.0.2的jdk,随着版本的升高可能不在适用,需要查看官方文档、

猜你喜欢

转载自www.cnblogs.com/future-dream/p/9690805.html