我正在使用Laravel连接到MySQL数据库。
我遇到了这个例外:
PDOException
SQLSTATE[HY000] [1049] Unknown database 'forge'
这是我的config.database.php
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'Anastasie',
'password' => 'A@Laurent',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
为什么错误引用PDO
数据库?为什么forge
数据库名称?我已经改变了。
我应该做些什么来告诉Laravel我正在使用MySQL数据库吗?
我发现了这一行
protected $table = 'users';
在我的user.php文件中,我已将其更改为
protected $table = 'user';
因为我的数据库中的表格是user
而不是users
我在路线
中写了这个Route::resource('users', 'UsersController');
我在控制器文件夹中添加了UsersController.php
和UsersController.php
里面我有这个:
class UsersController extends BaseController {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$users = User::all();
return View::make('users.index', compact('users'));
}
我将此网址称为http://localhost:8082/laravel/public/users/
我在Windows 7上使用Laravel 4.2
提前致谢
答案 0 :(得分:13)
您必须清除缓存(因为您的旧配置位于缓存文件中):
php artisan cache:clear
pdo错误来自Laravel使用pdo驱动程序连接到mysql
的事实答案 1 :(得分:3)
答案 2 :(得分:3)
听起来你在某个地方有一个特定于环境的配置文件会覆盖默认的数据库设置。可能 app / config / local / database.php 。
答案 3 :(得分:3)
php artisan cache:clear
。 答案 4 :(得分:3)
使用phpMyAdmin(或者你喜欢的任何东西),我刚刚创建了一个名为“forge”的数据库并重新运行了php artisan migrate命令,这一切都有效。
答案 5 :(得分:2)
注意:一旦发生我意外地在我的数据库名称之前有空格,例如mydatabase
而不是mydatabase
,phpmyadmin将不显示空格,但是如果从命令行运行它mysql的界面,例如mysql -u the_user -p
然后show databases
,你将能够看到空间。
答案 6 :(得分:2)
我完成了所有操作,但是没有用,我发现应该停止php artisan serve(Ctrl + C)并再次启动php artisan serve。
答案 7 :(得分:1)
我有同样的问题... 如果您已经设置了数据库名称和用户名,并在.env文件中正确传递了该文件,但仍无法正常运行,请在终端中运行打击代码:(这将清除以前应用程序留下的缓存)
php artisan cache:clear
,然后再次运行命令php artisan serve
(如果正在运行,请停止并再次运行)
答案 8 :(得分:1)
首先使用此命令清除缓存
php artisan cache:clear
然后使用此命令重新启动服务器
php artisan serve
答案 9 :(得分:1)
如果您使用过Homestead,请确保下面.env文件中的数据库名称
DB_DATABASE=homestead
与Homestead.yaml文件中的值相同。
databases:
- homestead
答案 10 :(得分:0)
在第四个解决方案中,这个问题得到了回答,但我更愿意再次回答,以不同的方式解释这一点。 我在 phpmyadmin 中创建了我的数据库,即 http://localhost/phpmyadmin,问题解决了。这是我的代码:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "myDbn2";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database created successfully<br>";
$sql = 'create table if not exists fruits (id integer , name text , color text
, price float) ;';
$conn->exec($sql);
echo 'the table created successfully </br>';
$sql2 = 'insert into fruits values (1 , "apple", "red" , 23.2);';
$conn->exec($sql2);
echo 'insert was successfully';
} catch (PDOException $e) {
echo $e->getMessage();
}
$conn = null;
?>
代码先创建一个数据库,然后创建一个表并在其中插入一条记录。 如果您不在 phpmyadmin 站点 中创建数据库,则会出现异常 你也不需要使用 sql 语句 CREATE DATABASE name ; 没有它也能工作。
答案 11 :(得分:0)
检查您在 WAMP 中的端口(它位于 phpMyAdmin 之上)与 DB_port
文件中的 .env
匹配。
我在 DB_port
的 .env
是 3306
。我在 WAMP (phpMyAdmin) 中的服务器端口是 3308
- 你应该匹配它们。
答案 12 :(得分:0)
写
SELECT distint_column_name,SUM(amount) FROM table_x group by distint_column_name
在您的终端中,它将被修复
答案 13 :(得分:0)
就我而言,该错误是由于端口号不正确(该错误肯定是由于凭据不正确,例如host/port/dbname/username/password
)。
解决方案:
.env
文件; config/database.php
。清除缓存
php artisan config:cache
运行迁移
php artisan migrate
答案 14 :(得分:0)
我在com.android.application
和.env.example
和.env
中的APP_NAME变量有空格,例如该应用程序。用app.php
和'
围绕它,并通过env文件将新生成的应用程序密钥设置为APP_KEY变量,然后用php artisan cache:clear
重新启动服务器,即可解决此问题
答案 15 :(得分:0)
清除缓存~ % cd /ect/
~ % vim host
199.232.68.133 raw.githubusercontent.com
,然后重新启动服务器php artisan cache:clear
php artisan serve
答案 16 :(得分:0)
我有几天这个问题,事实证明,如果我在phpMyAdmin中创建了数据库,Laravel不会看到它, 因此,我通过MySqlWorkbench创建了数据库,并且可以正常工作:)
答案 17 :(得分:0)
这是我对问题中描述的问题的回答。
在cmd中写:
php artisan cache:clear
然后尝试在您的终端中执行此代码
php artisan serve
注意: 这将再次启动服务器
答案 18 :(得分:0)
在我的特定情况下,我最终意识到,当Laravel试图通过3306连接时,我的phpMyAdmin正在使用端口3308。所以我的建议是确保您具有正确的连接字符串! >
答案 19 :(得分:0)
遇到这个问题很多次,请注意我正在通过Vagrant运行laravel。所以这里有适用于我的修复:
您可以尝试重新加载服务器而不是流浪汉(即MAMP)
答案 20 :(得分:0)
您需要在.env文件中(如果需要,请在.env.example中)修改数据库的名称。 我做了一点小小的改动就解决了我的问题。
答案 21 :(得分:0)
有时是因为DB_CONNECTION = mysql并且您要使用sqlite数据库。 解决方案是使DB_CONNECTION = sqlite。希望对您有帮助
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DijkstraAdjacencyMatrix {
public static void main(String[] args) {
Set<CityNode> cities = new HashSet<>();
CityNode a = new CityNode("A");
CityNode b = new CityNode("B");
CityNode c = new CityNode("C");
CityNode d = new CityNode("D");
CityNode e = new CityNode("E");
cities.addAll(List.of(a,b,c,d,e));
CitiesGraph graph = new CitiesGraph(cities);
graph.connectCities(a, b, 50);
graph.connectCities(b, c, 30);
graph.connectCities(c, d, 40);
graph.connectCities(d, e, 20);
graph.show();
FindPath findPath = new FindPath();
System.out.println(findPath.calculateShortestPath(graph, a, e)); //prints 140 as expected
//to add some complexity we need to construct a new CitiesGraph. It is not reusable
CityNode f = new CityNode("F");
cities.add(f);
graph = new CitiesGraph(cities);
graph.connectCities(a, b, 50);
graph.connectCities(b, c, 30);
graph.connectCities(c, d, 40);
graph.connectCities(d, e, 20);
graph.connectCities(b, f, 10);
graph.connectCities(f, d, 10);
graph.show();
System.out.println(findPath.calculateShortestPath(graph, a, e));//prints 90 as expected
}
}
class FindPath{
//map to hold distances of all node from origin. at the end this map should contain
//the shortest distance between origin (from) to all other nodes
Map<CityNode, Integer> distances;
//using Dijkstra algorithm
public int calculateShortestPath(CitiesGraph graph, CityNode from, CityNode to) {
//a container to hold which cities the algorithm has visited
Set<CityNode> settledCities = new HashSet<>();
//a container to hold which cities the algorithm has to visit
Set<CityNode> unsettledCities = new HashSet<>();
unsettledCities.add(from);
//map to hold distances of all node from origin. at the end this map should contain
//the shortest distance between origin (from) to all other nodes
distances = new HashMap<>();
//initialize map with values: 0 distance to origin, infinite distance to all others
//infinite means no connection between nodes
for(CityNode city :graph.getCities()){
int distance = city.equals(from) ? 0 : Integer.MAX_VALUE;
distances.put(city, distance);
}
while (unsettledCities.size() != 0) {
//get the unvisited city with the lowest distance
CityNode currentCity = getLowestDistanceCity(unsettledCities);
//remove from unvisited, add to visited
unsettledCities.remove(currentCity); settledCities.add(currentCity);
Collection<CityNode> connectedCities = graph.getCitiesConnectedTo(currentCity);
//iterate over connected city to update distance to each
for( CityNode city : connectedCities){
//check if new distance is shorted than the previously found distance
int distanceToCity = graph.getDistanceBetween(city, currentCity);
if(distanceToCity <= 0) {
continue;
}
if(distances.get(currentCity) + distanceToCity < distances.get(city)){
//if so, keep the shortest distance found
distances.put(city,distances.get(currentCity) + distanceToCity);
//if city has not been visited yet, add it to unsettledCities
if(! settledCities.contains(city)) {
unsettledCities.add(city);
}
}
}
}
return distances.get(to);
}
private CityNode getLowestDistanceCity(Set <CityNode> unsettledCities) {
return unsettledCities.stream()
.min((c1,c2)-> Integer.compare(distances.get(c1), distances.get(c2)))
.orElse(null);
}
}
class CityNode {
private static int counter =0;
private final String name;
//assign unique id to each node. safer than to rely on unique name
private final int id = counter ++;
public CityNode(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("City ");
sb.append(name).append(" (id=").append(id).append(")");
return sb.toString();
}
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if(o == null || !(o instanceof CityNode)) return false;
CityNode c = (CityNode) o;
return c.getName().equalsIgnoreCase(name) && id == c.getId();
}
@Override
public int hashCode() {
int hash = 31 * 7 + id;
return name == null ? hash : name.hashCode();
}
}
class CitiesGraph{
//use set which prevents duplicate entries
private final Set<CityNode> cities;
private final int[][] adjacencyMatrix;
private static final int NOT_CONNECTED = -1;
public CitiesGraph(Set<CityNode> cities) {
this.cities = cities;
adjacencyMatrix = new int[cities.size()][cities.size()];
//initialize matrix
for(int row = 0; row < adjacencyMatrix.length ; row++){
for(int col = 0; col < adjacencyMatrix[row].length ; col++){
adjacencyMatrix[row][col] = row == col ? 0 : NOT_CONNECTED ;
}
}
}
public void connectCities(CityNode city1, CityNode city2, int distance) {
//assuming undirected graph
adjacencyMatrix[city1.getId()][city2.getId()] = distance;
adjacencyMatrix[city2.getId()][city1.getId()] = distance;
}
public int getDistanceBetween(CityNode city1, CityNode city2) {
return adjacencyMatrix[city1.getId()][city2.getId()];
}
public Collection<CityNode> getCitiesConnectedTo(CityNode city) {
Collection<CityNode> connectedCities = new ArrayList<>();
//iterate over row representing city's connections
int column = 0;
for(int distance : adjacencyMatrix[city.getId()]){
if(distance != NOT_CONNECTED && distance > 0) {
connectedCities.add(getCityById(column));
}
column++;
}
return connectedCities;
}
public CityNode getCityById(int id) {
for (CityNode city : cities) {
if (city.getId() == id) return city;
}
return null;
}
public void show() {
for(int[] row : adjacencyMatrix){
System.out.println(Arrays.toString(row));
}
}
//get a copy of cities list
public Collection<CityNode> getCities(){
return new ArrayList<>(cities);
}
}
答案 22 :(得分:0)
确保laravel文件夹中没有重复的.evn文件。如果存在,请将其删除。只保留.evn文件。
答案 23 :(得分:0)
好的,找到解决方案。
在文件database.php中,默认情况下是“mysql”部分:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
您需要做的就是更改值:
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
按您的数据库名称(如果您没有,则必须创建一个)和该数据库用户名
像这样'database' => env('DB_DATABASE', 'MyDatabase'),
'username' => env('DB_USERNAME', 'MyUsername'),
答案 24 :(得分:-1)
我有同样的问题,我看到我的数据库列出了我的数据库名称,但不存在。
我手动创建了同名的数据库,然后运行这个对我有用的命令。
答案 25 :(得分:-3)
我遇到了同样的问题,这就是我解决错误的原因。
在:
$conn= mysqli_connect($server_name, $mysql_Username, $mysql_Password, $db_name);
在:
刚刚添加了""
;
$conn= "mysqli_connect($server_name, $mysql_Username, $mysql_Password, $db_name)";