DotNet,PHP,Java的数据库连接代码大全(带演示代码)
C#数据库连接字符串
Web.config文件
<connectionStrings> <!--SQLServer数据库连接--> <add name="conn_test_sqlserver" connectionString="server=127.0.0.1;uid=testuser;pwd=testPwd;database=db_test;pooling=true;min pool size=10;max pool size=1024;connection lifetime=300;packet size=1000" providerName="System.Data.SqlClient"/> <!--MySQL数据库连接--> <add name="conn_test_mysql" connectionString="Data Source=127.0.0.1; Database=db_test; User Id=testuser;Password=testPwd; pooling=false; CharSet=utf8; Port=3306" providerName="MySql.Data.MySqlClient"/> <!--SQLite数据库连接--> <add name="conn_test_sqlite" connectionString="Data Source=|DataDirectory|\db_test.db3; Pooling=true; FailIfMissing=false" providerName="System.Data.SQLite" /> </connectionStrings> <!-- 解决DbProviderFactories.GetFactory(ProviderName)出现的异常:“找不到请求的 .Net Framework Data Provider。可能没有安装。” --> <system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite"/> <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.105.2, Culture=neutral, PublicKeyToken=db937bc2d44ff139" /> <remove invariant="MySQL Data Provider"/> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data>
示例代码:
protected void Page_Load(object sender, EventArgs e) { try { object value = GetValue(); Response.Write(null==value?"Null":value); } catch (Exception ex) { Response.Write(ex.Message); } } public object GetValue() { string connName = "con_test_mysql"; System.Configuration.ConnectionStringSettings connConf = System.Configuration.ConfigurationManager.ConnectionStrings[connName]; DbFactory dbFactory = new DbFactory(connConf.ProviderName, connConf.ConnectionString); try { System.Data.Common.DbProviderFactory dbpf = System.Data.Common.DbProviderFactories.GetFactory(connConf.ProviderName); using (System.Data.Common.DbConnection conn = dbpf.CreateConnection()) { conn.ConnectionString = connConf.ConnectionString; using (System.Data.Common.DbCommand cmd = conn.CreateCommand()) { // cmd string sqlstmt = "select remark from t_user where account=@account"; cmd.CommandText = sqlstmt; cmd.CommandTimeout = 30; // params System.Data.Common.DbParameter dbpara = cmd.CreateParameter(); dbpara.ParameterName = "@account"; dbpara.Value = "test@email.com"; dbpara.Size = 16; cmd.Parameters.Add(dbpara); // execute System.Data.Common.DbDataAdapter dbadp = dbpf.CreateDataAdapter(); dbadp.SelectCommand = cmd; conn.Open(); DataTable dtResult = new DataTable(); dbadp.Fill(dtResult); object value = null; if (dtResult.Rows.Count > 0) { value = dtResult.Rows[0][0]; if (DBNull.Value == value) { value = null; } } return value; } } } catch (Exception ex) { throw ex; } }
下载: CSharpDbConnectionDemo(DotNet数据库连接演示).zip
Java数据库连接字符串
// mysql driver="com.mysql.jdbc.Driver"; url = "jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF8"; conn = getConnection(driver,url, "user", "password"); System.out.println("与mysql数据库连接" + (null == conn ? "失败" : "成功")); // sqlite driver="SQLite.JDBCDriver"; url = "jdbc:sqlite:/C:/db_test.db3"; conn = getConnection(driver,url); System.out.println("与sqlite数据库连接" + (null == conn ? "失败" : "成功")); // sqlserver driver="com.mysql.jdbc.Driver"; url = "jdbc:sqlserver://localhost:1433;DatabaseName=db_test"; conn = getConnection(driver,url, "user", "password"); System.out.println("与sql server数据库连接" + (null == conn ? "失败" : "成功")); // oracle driver="oracle.jdbc.driver.OracleDriver"; url = "jdbc:oracle:thin:@localhost:1521:orcl"; conn = getConnection(driver,url, "user", "password"); System.out.println("与oracle数据库连接" + (null == conn ? "失败" : "成功"));
JDBC连接数据库方法
public static Connection getConnection(String driver, String url, String user, String password) { Connection conn = null; try { //初始化驱动包 Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return conn; }
下载:[jdbc_connection_demo(JDBC连接各种数据库演示).zip]
PHP_PDO数据库连接字符串
// PDO连接MySQL的DSN字符串 (需要打开php配置文件中的"extension=php_pdo_mysql.dll"选项) mysql:dbname=db_test;host=127.0.0.1;port=3306;charset=utf8 // PDO连接SQLite的DSN字符串 (需要打开php配置文件中的"extension=php_pdo_sqlite.dll"选项) sqlite:test_db.db3 // PDO通过ODBC连接SQL Server的DSN字符串 (需要打开php配置文件中的"extension=php_pdo_odbc.dll"选项) odbc:Driver={SQL Server};Server=127.0.0.1,1433;Database=db_test; // PDO连接SQL Server的DSN字符串(配置非常麻烦,建议使用ODBC方式。PHP5.3.6以上的版本中php_mssql.dll,php_pdo_mssql.dll都已经不见了,只有一个php_pdo_odbc.dll,所以最新最好的php连接mssql方法应该是使用ODBC的驱动模式。) sqlsrv:Database=db_test;Server=127.0.0.1,1433 // PDO连接PostgreSQL的DSN字符串 (需要打开php配置文件中的"extension=php_pdo_pgsql.dll"选项) pgsql:dbname=db_test;host=127.0.0.1;port=5432 // PDO连接Oracle的DSN字符串 (需要打开php配置文件中的"extension=php_pdo_oci.dll"选项) oci:dbname=//127.0.0.1:5432/db_test
示例代码:
$dsn = 'mysql:dbname=db_test;host=127.0.0.1;port=3306;charset=utf8'; $pdo = new PDO($dsn, 'dbuser', 'dbpwd'); $stmt = $pdo->prepare('select id, name from t_user where user_name=:account'); $stmt->bindParam(':account', $account); $stmt->execute(); while ($row = $stmt->fetch()) { return $row; }
/** * 查询并返回数组 * <br />例如: * <br />query('select COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, EXTRA, COLUMN_COMMENT from information_schema.columns WHERE TABLE_SCHEMA=:database AND TABLE_NAME=:table', ['database' => $dbname, 'table' => $tablename]) * @param string $sqlstmt * @param array $params * @return array */ function query($sqlstmt, $params = []) { $dsn = 'mysql:host=127.0.0.1;port=3306;charset=utf8'; $pdo = new PDO($dsn, 'dbuser', 'dbpwd'); $stmt = $pdo->prepare($sqlstmt); if ($params) { $names = array_keys($params); $values = array_values($params); $i = count($names) - 1; // 这里不能用foreach,参考bindParam陷阱(值参数是引用型变量):http://www.laruence.com/2012/10/16/2831.html while ($i >= 0) { $stmt->bindParam($names[$i], $values[$i]); $i--; } } $stmt->execute(); $out = []; while ($row = $stmt->fetch()) { $out[] = $row; } return $out; }
下载:[pdo_dns_demo(PDO连接各种数据库演示).zip]
PHP官方DSN说明:http://php.net/manual/en/ref.pdo-odbc.connection.php
更多DSN连接字符串可以参考:http://www.connectionstrings.com/
版权声明:本文采用署名-非商业性使用-相同方式共享(CC BY-NC-SA 3.0 CN)国际许可协议进行许可,转载请注明作者及出处。 |