Java基础知识➣发送Emai和访问MySQL数据库(七)

时间:2021-12-21 20:00:45

概述

  Java程序发送 E-mail 十分简单,但是首先你应该在你的机器上安装 JavaMail API 和Java Activation Framework (JAF) 。Java访问数据则需要 使用JDBC 连接 MySQL 数据库。JDBC起到数据库驱动作用。

E-Mail的发送

  第三方包的下载地址方式,加载之后在对应的项目中导入该库文件。

  以下是下载之后,编写测试代码,能够借助网易smtp服务发邮件:

package CommClass;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailCommClass {
public static void SendEmail()
{
String to
="txxxxx@qq.com";
String
from="fxxxx@163.com";
String host
="smtp.163.com";
Properties properties
=System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put(
"mail.smtp.auth", "true");

properties.setProperty(
"mail.user", "fxxxx@163.com");
properties.setProperty(
"mail.password", "fxxxx");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator()
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("fxxxx@163.com", "fxxxx"); //发件人邮件用户名、密码
}
});
try{
MimeMessage message
=new MimeMessage(session);
message.setFrom(
new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(
"This is the Subject Line !");
message.setText(
"This is actual message");
Transport.send(message);
System.
out.println("Sent Message Successfully....");

}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

MySQL链接

  Java 连接 MySQL 需要驱动包,最新版下载地址为:http://dev.mysql.com/downloads/connector/j/,解压后得到jar库文件,然后在对应的项目中导入该库文件。

  以下实例使用了 JDBC 连接 MySQL 数据库:

package CommClass;

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


public class MySQLHelper {
// JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.168.1.102:3306/ruidb";

// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "root";

public static void OpeartDB()
{
Connection conn
=null;
Statement stmt
=null;
try{
// Class.forName(JDBC_DRIVER);
System.out.println("连接数据库...");

conn
=DriverManager.getConnection(DB_URL,USER,PASS);
System.
out.println("实例化Statement对....");
stmt
=conn.createStatement();
String sql
="SELECT * from t_student";
ResultSet rs
=stmt.executeQuery(sql);
while(rs.next())
{
int id=rs.getInt("ID");
String tname
=rs.getString("Name");
System.
out.printf("ID:%d,Num:%s",id,tname);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}
catch(SQLException se2){
}
// 什么都不做
try{
if(conn!=null) conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}

}
}